Check if a method exists in the same class

So method_exists() requires the object to see if the method exists. But I want to know if a method from one class exists.

I have a method that processes some information and can receive an action that triggers a method to further process this information. I want to check if a method exists before calling it. How can i achieve this?

Example:

 class Foo{ public function bar($info, $action = null){ //Process Info $this->$action(); } } 
+6
source share
4 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(); 
+22
source

Using method_exists correct. However, if you want to comply with the "Interface Separation Principle", you will create an interface to perform introspection, for example:

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

method_exists() takes a class name or an instance of an object as a parameter. So you can check $this

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

Parameters ΒΆ

object An instance of an object or class name

method_name Method name

+2
source

The best way, in my opinion, is to use the __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 an internal PHP method.

+1
source

All Articles