Reputation: 2011
Say I have a callable stored as a variable:
$callable = function($foo = 'bar', $baz = ...) { return...; }
How would I get 'bar'?
if (is_callable($callable)) {
return func_get_args();
}
Unfortunately func_get_args()
is for the current function, is it possible to get a key value pair of arguments?
Upvotes: 4
Views: 3237
Reputation: 2393
I came across this question because I was looking for getting the arguments for a callable which is not just the function itself. My case is
class MyClass{
public function f(){
// do some stuff
}
}
$myclass = new MyClass();
$callable = array($myclass, "f);
This is a valid callback in php. In this case the solution given by @Marek does not work.
I worked around with phps is_callable
function. You can get the name of the function by using the third parameter. Then you have to check whether your callback is a function or a (class/object) method. Otherwise the Reflection
-classes will mess up.
if($callable instanceof Closure){
$name = "";
is_callable($callable, false, $name);
if(strpos($name, "::") !== false){
$r = new ReflectionMethod($name);
}
else{
$r = new ReflectionFunction($name);
}
}
else{
$r = new ReflectionFunction($callable);
}
$parameters = $r->getParameters();
// ...
This also returns the correct value for ReflectionFunctionAbstract::isStatic()
even though the $name
always uses ::
which normally indicates a static function (with some exceptions).
Note: In PHP>=7.0 this may be easier using Closures
. There you can do someting like
$closure = Closure::fromCallable($callable);
$r = new ReflectionFunction($closure);
You may also cause have to distinguish between ReflectionFunction
and ReflectionMethod
but I can't test this because I am not using PHP>=7.0.
Upvotes: 3
Reputation: 7433
You can use reflection:
$f = new ReflectionFunction($callable);
$params = $f->getParameters();
echo $params[0]->getDefaultValue();
Upvotes: 5
Reputation: 5403
You may want to use get_defined_vars to accomplish this, this function will return an array of all defined variables, specifically by accessing the callable
index from the output array.
Upvotes: 1