运行前动态检查可用的方法


Dynamically check for available method before running

我试图减少API类上的代码,我要做的是确保在调用类内部的方法之前存在方法。

将方法作为变量传递,需要查看该方法是否存在于类中,然后运行该方法。

示例代码:

<?php
    class Test {
    private $data;
    private $obj;
    public function __contruct($action,$postArray)
    {
        $this->data = $postArray;
        if (method_exists($this->obj, $action)) {
            //call method here
            //This is where it fails
            $this->$action;
        }else{
            die('Method does not exist');
        }
    }
    public function methodExists(){
        echo '<pre>';
        print_r($this->data);
        echo '</pre>';
    }
}
//should run the method in the class
$test = new Test('methodExists',array('item'=>1,'blah'=>'agadgagadg'));
//should die()
$test2 = new  Test('methodNotExists',array('item'=>1,'blah'=>'agadgagadg'));
?>

这可能吗?

您只需要将$this->$action更改为$this->{$action}();就可以了。

这里有更深入的答案,包括call_user_func

你有一个错别字在你的构造函数的名称,第二,当调用method_exists()函数你应该传递$this作为第一个参数,而不是$this->obj:

public function __construct($action,$postArray)
    {
        $this->data = $postArray;
        if (method_exists($this, $action)) {
            $this->{$action}();
        }else{
            die('Method does not exist');
        }
    }