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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33938206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:40:19  来源:igfitidea点击:

Check if method exists in the same class

phpclassmethodsexists

提问by Rafael

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.

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

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

回答by Rajdeep Paul

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

回答by Flosculus

Using method_existsis correct. However if you want to conform to the "Interface Segregation Principle", you will create an interface to perform introspection against, like so:

使用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()

回答by Calimero

method_exists()accepts either a class name or object instance as a parameter. So you could check against $this

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

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

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

Parameters?

objectAn object instance or a class name

method_nameThe method name

参数?

object对象实例或类名

method_name方法名

回答by Jeliu Jelev

The best way in my opinion is to use __call magic method.

我认为最好的方法是使用 __call 魔术方法。

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

Yes, you can use method_exists($this ...) but this is the internal PHP way.

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