如何知道方法有多少参数?

时间:2012-02-17 14:35:21

标签: php oop reflection

可能使用ReflectionClass,我怎么知道方法有多少参数?

class Test {
    public function mymethod($one, $two, $three = '') {}
    public function anothermethod($four) {}
}

$test = new Test();
$i = function_im_looking_for(array($test, 'mymethod'));
$i2 = function_im_looking_for(array($test, 'anothermethod'));
echo $i .' - '. $i2;

以上代码应输出:3 - 1;

2 个答案:

答案 0 :(得分:4)

function function_im_looking_for($callable) {
    list($class, $method) = $callable;
    $reflector = new ReflectionMethod($class, $method);
    return $reflector->getNumberOfParameters();
}

这一切都只是找到ReflectionMethod

答案 1 :(得分:3)

您可以使用refelectClass的getParameters()方法,然后将其计算为:

$refMethod = new ReflectionMethod('className',  'functionName');
$params = $refMethod->getParameters();
echo count($params);

Working Example