如何知道一个方法需要多少个参数


How to know how many parameters a method is expecting?

可能使用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

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

这一切都只是为了找到ReflectionMethod

您可以使用refelectClass的getParameters()方法,然后对其进行计数,例如:

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

工作示例