How can I determine the number of arguments that a closure is declared with for use outside of the closure? for example:
$myClosure = function($arg1, $arg2, $arg3){
}
$numArgs = someMagicalFunction($myClosure);
echo("that closure expects $numArgs arguments");
Is there some function that does what I need?
Anonymous functions Anonymous functions, also known as closures, allow the creation of functions which have no specified name. Anonymous functions are implemented using the Closure class. Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class.
Closures have been introduced in PHP 5.3 and their most important use is for callback functions. Basically a closure in PHP is a function that can be created without a specified name - an anonymous function. Here's a closure function created as the second parameter of array_walk ().
Anonymous functions. Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Anonymous functions are implemented using the Closure class. Example #1 Anonymous function example.
It's possible for multiple functions to share the same closure, and they can have access to multiple closures as long as they are within their accessible scope. In PHP, a closure is a callable class, to which you've bound your parameters manually.
Use reflection. See this article: http://www.bossduck.com/2009/07/php-5-3-closures-and-reflection/
$func = function($one, $two = 'test') {
echo 'test function ran'.PHP_EOL;
};
$info = new ReflectionFunction($func);
var_dump(
$info->getName(),
$info->getNumberOfParameters(),
$info->getNumberOfRequiredParameters()
);
Which returns:
string(9) "{closure}"
int(2)
int(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With