简体   繁体   English

运行前动态检查可用方法

[英]Dynamically check for available method before running

I am trying to reduce code on an API class, what I am looking to do is to make sure a method exists before calling the method inside of the class. 我正在尝试减少API类上的代码,我要做的是在调用类内部的方法之前确保方法存在。

Will be passing a method as a variable need to see if that method exists inside of the class then run the method. 将作为变量传递方法时,需要查看该方法是否存在于类中,然后运行该方法。

Sample code below: 下面的示例代码:

<?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'));
?>

Is this even possible? 这有可能吗?

You just need to change $this->$action to $this->{$action}(); 您只需要将$this->$action更改$this->$action $this->{$action}(); and it should work. 它应该工作。

More in depth answer here including call_user_func 这里有更深入的答案,包括call_user_func

You have a typo in the name of your constructor function and second, when calling the method_exists() function you should be passing $this as the first parameter, not $this->obj : 您在构造函数的名称中有一个错字,其次,在调用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');
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM