douzhan1868
2014-04-22 10:59
浏览 37
已采纳

获取类方法的参数数量

I know:

function params($fn) {
    $R = new ReflectionFunction($fn);
    return $R->getNumberOfParameters();
}

returns the number of parameters the function can accept, but how do I do this for a method that exists in a class?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongqin8652 2014-04-22 11:09
    已采纳

    You can for instance add a new parameter $clazz to your function, in order to give a scope to the method you want to know the number of arguments. Instead of using ReflectionFunction, use ReflectionClass in addition with ReflectionMethod.

    function params($clazz, $method) { 
        $C = new ReflectionClass($clazz);
        $M = $C->getMethod($method);
        return $M->getNumberOfParameters();
    }
    
    点赞 打赏 评论
  • doubailian4459 2014-04-22 11:21

    You could extend the function by accepting a callable:

    function params(callable $fn)
    {
        if (is_string($fn) || $fn instanceof \Closure) {
            $r = new ReflectionFunction($fn);
        } elseif (is_array($fn)) {
            if (is_object($fn[0])) {
                $c = new ReflectionObject($fn[0]);
            } else { // assume string
                $c = new ReflectionClass($fn[0]);
            }
            $r = $c->getMethod($fn[1]);
        }
        return $r->getNumberOfParameters();
    }
    
    params(['Foo', 'bar']); // get nr of arguments for Foo::bar()
    params([new Foo, 'bar']); // get nr of arguments for $foo->bar()
    params('foo'); // get nr of arguments for foo()
    // ...
    
    点赞 打赏 评论

相关推荐 更多相似问题