Reputation: 7643
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.
Upvotes: 3
Views: 3973
Reputation: 1565
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
}
Upvotes: 5
Reputation: 468
Your correct about using the Magic method __call(), but you are implementing it wrong.
This is how you should implement the __call magic method for your purpose.
public function __call($name, $arguments) {
if(method_exists($this->obj,$name)) {
return call_user_func_array(array($this->obj, $name), $arguments);
} else {
throw new Exception("Undefined method ".get_class($this)."::".$name);
}
}
Upvotes: 0
Reputation: 7643
Thanks to Mark Baker I found the solution. In case anyone else has similar problem the following solved it:
added this function inside my factory class
public function __call($name, $arguments)
{
//if function exists within this class call it
if (method_exists(self, $name))
{
$this->$name($arguments);
}
else
{
//otherwise check if function exists in obj and call it
if (method_exists($this->obj, $name))
{
$this->obj->$name($arguments);
}
else
{
throw new \Exception('Undefined function call.');
}
}
}
Upvotes: 1
Reputation: 7447
To checks if the class method exists or not:
$this->obj = new ClassA();
var_dump(method_exists($this->obj,'callMe'));
if it is static method:
var_dump(method_exists('ClassA','callMe'));
Returns true
if the method given by method_name has been defined for the given object, false
otherwise.
Upvotes: 0