I've been searching alot, but I could not find any solution. I also don't exactly know if this is possible.
So here I have 2 cases somebody could do:
Case 1:
$callback = function(Object $obj, $var) {
// Do stuff
}
Case 2:
$callback = function($var) {
// Do stuff
}
Now I will call the function like this:
call_user_func_array($callback, [new Object, 'some text'])
But now there is a problem. In case 2 the $var
will be seen as the object parameter. How do I send only the string parameter to the call when the object isn't used? And I don't want the order to change, the Object must be first.
P.S. I noticed that this is possible in the Symfony framework. I will continue researching how Symfony does this, any tips are appreciated!
Thanks for reading!
You can use reflection.
Example:
function call(callable $callback, $var, object $obj = null)
{
$callbackArguments = array();
$parameters = (new ReflectionFunction($callback))->getParameters();
foreach ($parameters as $parameter) {
if ($parameter->getType() == 'object') {
$callbackArguments[] = $obj;
} else {
$callbackArguments[] = $var;
}
}
return call_user_func_array($callback, $callbackArguments);
}