I need to be able to call a method without having to know whether or not it is static.
For example, this doesn’t work and I would like it to:
class Groups {
public function fetchAll($arg1, $arg2){
return $this->otherFunction();
}
public static function alsoFetchAll($arg1, $arg2){}
}
$arguments = array('one', 'two');
$result = call_user_func_array(array('Groups', 'fetchAll'), $arguments);
$result = call_user_func_array(array('Groups', 'alsoFetchAll'), $arguments);
I’m getting an error for the instance varirable:
Fatal error: Using $this when not in object context
The reason it doesn’t work is because I need to instantiate the class for the instance variables to work. But my constructor doesn’t take any arguments so I want a quick way to skip this step.
How can I write this so that it doesn’t matter what kind of method it is?
You can do this with Reflection. Assuming you have these variables:
Then you can create a new instance of the class:
And call both methods the same way, checking if they’re static or not for completeness:
However, you don’t need to make sure they’re static, you can just as easily do this, regardless of whether or not the method is static:
You can see it working in this demo.
Edit: Here is a demo showing that this works with the OP’s use case, without any errors / warnings / notices.