【问题标题】:PHP call method from class dynamically从类动态调用PHP方法
【发布时间】:2014-07-12 21:15:18
【问题描述】:
class Test {

    function index($method, $params) {

        if (!method_exists($this, $method)) { 
            $result = 'method does not exist!';
        }
        else {
            switch ($method) {
                case 'add':
                    $result = $this->add($params[0], $params[1], $params[2]);
                break;
                case 'sub':
                    $result = $this->sub($params[0], $params[1]);
                break;
                default:
                    $result = 'no method selected!';
                break;
            }
        }       
        return $result;

    }

    public function add($n1, $n2, $n3) {
        return $n1 + $n2;
    }

    public function sub($n1, $n2) {
        return $n1 - $n2;
    }

}

如何以其他方式调用方法。我不想使用 switch,因为当我添加新方法时,我也必须将它添加到 switch。我想避免这种情况。

问:如何动态调用类中的方法?

我的想法:

if(!function_exists($method)){
    $result = 'function not exist!';
}
else {
    $result = call_user_func_array($method, $params);
}  

【问题讨论】:

  • $result = call_user_func_array(array('Test', $method), $params); - 有关回调的详细信息,请参阅 the docs

标签: php methods call


【解决方案1】:

嗯,我错了……

您应该将开关替换为:

call_user_func_array(array($this, $method), $params);

【讨论】:

  • 你真的应该添加一些关于你的代码如何/为什么工作的解释
【解决方案2】:

好吧,你可以这样做,

function index($method, $params) {

    if (!method_exists($this, $method)) { 
        $result = 'method does not exist!';
    } else {

        $result = call_user_func_array(array($this, $method), $params);
       }
    }

    return $result;
}

【讨论】:

    猜你喜欢
    • 2010-09-20
    • 2010-09-21
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2011-01-07
    • 1970-01-01
    相关资源
    最近更新 更多