Check if method exists in the same class

37,803

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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

Share:
37,803
Rafael
Author by

Rafael

Updated on April 21, 2020

Comments

  • Rafael
    Rafael about 4 years

    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();
        }
    }
    
  • Rafael
    Rafael over 8 years
    I think you gave me a link to the manual to support what you said, but in the manual it says it needs an OBJECT. I'll try what you said, back in a moment...
  • Calimero
    Calimero over 8 years
    highlighting the interesting part above for you
  • Rafael
    Rafael over 8 years
    Ow, (face in the ground), sorry =p
  • Flosculus
    Flosculus over 8 years
    @Rafael Don't you just love OOP.
  • Rafael
    Rafael over 8 years
    I was starting to, but you killed it @Flosculus
  • Jacky Supit
    Jacky Supit over 6 years
    i just knew that PHP has an interface and you can implement it. thought we can do that only in java lol. thanks dude
  • P. Kouvarakis
    P. Kouvarakis over 3 years
    That won't help if A extends B and you have no control of B (it is provided by 3rd party)