问题描述
是否可以在 PHP 中获取匿名函数预期的参数数量?我知道 ReflectionMethod,但这似乎只有在该方法是在类上定义时才有效.就我而言,匿名函数要么有 1 个参数,要么有两个参数.我更愿意正确地进行检查,而不是将第一个调用包装在 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();
}
几个月前,我在这里写了更详细的内容:http://onehackoranother.com/logfile/2009/05/finding-the-arity-of-a-closure-in-php-53
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
这篇关于如何动态检查 PHP 中匿名函数的预期参数数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!