You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP数组存储对象方法时自动调用所有方法问题及方案咨询

问题描述

我编写了如下辅助方法:

private function continueConv($attribute, $next): void
{
    $sequence = [   $this->askName(),
                    $this->askEmail(),
                    $this->askPhone(),
                    $this->manageMessage()
                ];

    match($attribute) {
        'user_name' => $sequence[0 + (int)$next], 
        'user_email' => $sequence[1 + (int)$next], 
        'user_phone' => $sequence[2 + (int)$next]
    };

    return;
}

发现解释器计算$sequence数组时,并未仅存储方法指针,而是直接调用了所有方法!这是Bug吗?是否有可行的替代方案?


编辑:可行但不够理想的方案

我找到了一个可行的替代方案,但灵活性不足:

private function continueConv($attribute, $next): void
{

    match($attribute) {
        'user_name' => $next ? $this->askEmail() : $this->askName(), 
        'user_email' => $next ? $this->askPhone() : $this->askEmail(), 
        'user_phone' => $next ? $this->manageMessage() : $this->askPhone()
    };

    return;
}

但我更希望使用方法数组的形式,以便轻松调整执行顺序。


更新:优化后的最终代码

经过调整,我得到了更符合需求的优化代码:

protected $sequence = [ "run", "askQuestion", "askName", "askEmail", "askPhone", "manageMessage" ];


private function continueConv($fnName, $next): void
{
    $idx = array_search($fnName, $this->sequence) ?: 0;
    $call = [$this, $this->sequence[$idx + (int)$next]]();
}

感谢各位帮助!


内容的提问来源于stack exchange,提问作者Valentino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:44:16