Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if method exists in the same class

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();     } } 
like image 682
Rafael Avatar asked Nov 26 '15 12:11

Rafael


People also ask

How do you check if a method is in a class python?

The Python's isinstance() function checks whether the object or variable is an instance of the specified class type or data type. For example, isinstance(name, str) checks if name is an instance of a class str .

How do you check if a class has a method PHP?

Use the PHP method_exists() function to check if an object or a class has a specified method.

Does function exist in Java?

You can find out if a method exists in Java using reflection. Get the Class object of the class you're interested in and call getMethod() with the method name and parameter types on it. If the method doesn't exist, it will throw a NoSuchMethodException . Also, please note that "functions" are called methods in Java.


2 Answers

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(); 
like image 53
Rajdeep Paul Avatar answered Sep 18 '22 12:09

Rajdeep Paul


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() 
like image 45
Flosculus Avatar answered Sep 19 '22 12:09

Flosculus