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

Is it possible to get the number of arguments expected from an anonymous function in PHP? I know ReflectMethod, but this only works if the method is defined in the class. In my case, an anonymous function will either have one or two arguments. I would prefer to do the check correctly, instead of wrapping the first call in try / catch and retrying with two parameters if the first fails.

+3
source share
1 answer

Try the following:

// 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

+5

Source: https://habr.com/ru/post/1730796/


All Articles