开发者

How can I dynamically check the number of arguments expected of an anonymous function in PHP?

开发者 https://www.devze.com 2022-12-18 10:55 出处:网络
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.

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

精彩评论

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

关注公众号