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

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.

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}(); and it should work.

More in depth answer here including 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:

public function __construct($action,$postArray)
    {

        $this->data = $postArray;
        if (method_exists($this, $action)) {
            $this->{$action}();

        }else{
            die('Method does not exist');
        }
    }