Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect if function exists within the class and if not call a different function. PHP

I know there are other ways around this but just for the sake of simplicity I would like to know if its possible to do something like:

   MyFactory::Create()->callMe();

and myFactory class:

   class MyFactory {
       private $obj;

       public static Create() { 
           $this->obj = new ClassA();
           return $this->obj;
       }

       public function __undefinedFunctionCall() {
           //function does not exist within MyFactory Class but it exists
           // in ClassA
           $this->obj->callMe();
       }
   }

so basically the function callMe does not exist within MyFactory class but it exists in ClassA. Dont ask me why I cant just extend classA because the code structure is already written and its not up to me to modify it. I just need a way around it.

like image 439
GGio Avatar asked Jan 27 '26 23:01

GGio


1 Answers

You could simply use method_exists

It takes 2 parameters method_exists ( mixed $object, string $method_name )

The first is an object instance or a class name, and the second is The method name.

So it should be as simple as:

if(method_exists($this->obj,'callMe')){
   $this->obj->callMe();
}
else{
//...throw error do some logic
}
like image 69
Stephan Avatar answered Jan 29 '26 13:01

Stephan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!