2013-03-06 23 views
3

如何確定閉包被聲明的參數的數量,以便在閉包之外使用?例如:如何確定PHP中閉包/匿名函數的參數數量

$myClosure = function($arg1, $arg2, $arg3){ 

} 

$numArgs = someMagicalFunction($myClosure); 
echo("that closure expects $numArgs arguments"); 

是否有一些功能可以滿足我的需求?

回答

6

使用反射。看到這篇文章:http://www.bossduck.com/2009/07/php-5-3-closures-and-reflection/

$func = function($one, $two = 'test') { 
    echo 'test function ran'.PHP_EOL; 
}; 
$info = new ReflectionFunction($func); 
var_dump(
    $info->getName(), 
    $info->getNumberOfParameters(), 
    $info->getNumberOfRequiredParameters() 
); 

將返回:

string(9) "{closure}" 
int(2) 
int(1)