如何动态检查PHP中匿名函数的预期参数数量?

Jos*_*ton 3 php reflection arguments anonymous-function

是否有可能获得PHP中匿名函数所需的参数数量?我知道ReflectionMethod,但这似乎只有在类上定义方法时才有效.在我的例子中,匿名函数要么有1个或两个参数.我更喜欢正确地进行检查,而不是将第一个调用包装在try/catch中,如果第一个调用失败则再次尝试使用2个参数.

小智 5

试试这个:

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

几个月前,我在这里更详细地写了这篇文章:http://onehackoranother.com/logfile/2009/05/finding-the-arity-of-a-closure-in-php-53