Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to determine number of arguments for a closure/anonymous function in PHP

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?

like image 429
DiverseAndRemote.com Avatar asked Mar 06 '13 20:03

DiverseAndRemote.com


People also ask

What is an anonymous function in PHP?

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.

What are closures in PHP and how to use them?

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 ().

What are anonymous functions in C++?

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.

Can multiple functions share the same closure in PHP?

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.


1 Answers

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)
like image 67
Tomasz Kowalczyk Avatar answered Nov 01 '22 08:11

Tomasz Kowalczyk