问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/2173760/how-can-i-dynamically-check-the-number-of-arguments-expected-of-an-anonymous-fun