如何动态检查预计在PHP匿名函数的参数的数量? [英] How can I dynamically check the number of arguments expected of an anonymous function in PHP?
问题描述
是否有可能获得的预期PHP匿名函数的参数个数?我知道ReflectionMethod的,但似乎如果该方法是在一个类定义为仅工作。就我而言,匿名函数要么将有1个或两个参数。我想preFER做检查正常,而不是在一个try / catch包裹第一个呼叫,并与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.
推荐答案
试试这个:
// returns the arity of the given closure
function arity($lambda) {
$r = new ReflectionObject($lambda);
$m = $r->getMethod('__invoke');
return $m->getNumberOfParameters();
}
几个月前,我这里稍微详细地写了起来:<一href=\"http://onehackoranother.com/logfile/2009/05/finding-the-arity-of-a-closure-in-php-53\">http://onehackoranother.com/logfile/2009/05/finding-the-arity-of-a-closure-in-php-53
这篇关于如何动态检查预计在PHP匿名函数的参数的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!