在运行之前动态检查可用方法

时间:2015-10-08 18:20:05

标签: php validation class

我正在尝试减少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'));
?>

这甚至可能吗?

2 个答案:

答案 0 :(得分:1)

您只需将$this->$action更改为$this->{$action}();即可。

More in depth answer here including call_user_func

答案 1 :(得分:0)

您的构造函数名称中有一个拼写错误;其次,在调用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');
        }
    }
相关问题