开发者

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 defi开发者_高级运维ned 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜