Check if method exists in the same class

后端 未结 4 757
闹比i
闹比i 2020-12-06 09:18

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

相关标签:
4条回答
  • 2020-12-06 09:51

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

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

    Parameters

    object An object instance or a class name

    method_name The method name

    0 讨论(0)
  • 2020-12-06 10:02

    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();
    
    0 讨论(0)
  • 2020-12-06 10:03

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

    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.

    0 讨论(0)
  • 2020-12-06 10:08

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

    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()
    
    0 讨论(0)
提交回复
热议问题