Josh Smeaton
Josh Smeaton

Reputation: 48730

How can I dynamically check the number of arguments expected of an anonymous function in PHP?

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.

Upvotes: 4

Views: 630

Answers (1)

jaz303
jaz303

Reputation: 1136

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

Upvotes: 7

Related Questions