Check if method exists in the same class

Rafael picture Rafael · Nov 26, 2015 · Viewed 32.6k times · Source

So, method_exists() requires an object to see if a method exists. But I want to know if a method exists from within the same class.

I have a method that process some info and can receive an action, that runs a method to further process that info. I want to check if the method exists before calling it. How can I achieve it?

Example:

class Foo{
    public function bar($info, $action = null){
        //Process Info
        $this->$action();
    }
}

Answer

Rajdeep Paul picture Rajdeep Paul · Nov 26, 2015

You can do something like this:

class A{
    public function foo(){
        echo "foo";
    }

    public function bar(){
        if(method_exists($this, 'foo')){
            echo "method exists";
        }else{
            echo "method does not exist";
        }
    }
}

$obj = new A;
$obj->bar();