检查方法是否存在于同一个类中

2021-12-23 00:00:00 class methods php exists

因此,method_exists() 需要一个对象来查看方法是否存在.但是我想知道同一个类中是否存在一个方法.

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?

示例:

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

推荐答案

你可以这样做:

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();

相关文章