views:

61

answers:

2

Is it possible to get the number of arguments expected of an anonymous function in PHP? I'm aware of ReflectionMethod, but that seems to only work if the method is defined on a class. In my case, the anonymous function is either going to have 1 or two arguments. I'd prefer to do the checking correctly, rather than wrapping the first call in a try/catch, and trying again with 2 parameters if the first has failed.

A: 

Try with this.

metrobalderas
He doesn't mean take an undecided number of arguments, find out how many arguments an anonymous function has.
Chacha102
+4  A: 

Try this:

// returns the arity of the given closure
function arity($lambda) {
    $r = new ReflectionObject($lambda);
    $m = $r->getMethod('__invoke');
    return $m->getNumberOfParameters();
}

A few months ago I wrote this up in a bit more detail here: http://onehackoranother.com/logfile/2009/05/finding-the-arity-of-a-closure-in-php-53

jaz303
Just a note, this method shouldn't be relied upon as it is an implementation detail, according to PHP Documentation.
Chacha102
Do you have a reference? I was under the impression __invoke() was an official "magic method": http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke - unless there's some specific exception regarding closures
jaz303
Fantastic, exactly what I needed, thank you! I was looking through the Reflection doco, but it was the _invoke key I was missing.
Josh Smeaton