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


Check if method exists in the same class

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

我有一个处理一些信息的方法,可以接收一个操作,运行一个方法来进一步处理这些信息。在调用该方法之前,我想检查它是否存在。如何实现它?

示例:

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

使用method_exists是正确的。然而,如果你想遵守"接口分离原则",你将创建一个接口来执行内省,比如:

class A
{
    public function doA()
    {
        if ($this instanceof X) {
            $this->doX();
        }
        // statement
    }
}
interface X
{
    public function doX();
}
class B extends A implements X
{
    public function doX()
    {
        // statement
    }
}
$a = new A();
$a->doA();
// Does A::doA() only
$b = new B();
$b->doA();
// Does B::doX(), then remainder of A::doA()

method_exists()接受类名或对象实例作为参数。所以你可以对照$this 进行检查

http://php.net/manual/en/function.method-exists.php

参数

对象对象实例或类名

方法名称方法名称

在我看来,最好的方法是使用__call魔术方法。

public function __call($name, $arguments)
{
    throw new Exception("Method {$name} is not supported.");
}

是的,您可以使用method_exists($this…),但这是PHP内部的方法。