检查闭包的参数个数

时间:2014-08-25 22:25:11

标签: php

我想检查stdClass的单​​个方法所具有的参数个数,所以当我遍历该对象时,我想检查当前元素是否是一个方法,如果是,它有多少个参数。

// Instantiate the object:
   $foo = new stdClass();

// Properties:
   $foo->ppt_1 = "My property type of STRING";
   $foo->ppt_2 = 100;

// Methods:
   $foo->mtd_1 = function( $fn, $ln ){ echo "Hello $fn $ln, this is printed by mtd_1()!"; };
   $foo->mtd_2 = function(){ echo "Hello again, this is printed by mtd_2()!"; };
   $foo->mtd_3 = function( $wd ){ echo "Hello $wd, this is printed by mtd_3()!"; };

// I tried something like this:
foreach( $foo as $k => $v ) {
   if( $v instanceof Closure ){
     if( /*Check if the number of parameters is equal to 1*/ ){
         $v( 'World' );
     }
     elseif( /*Check if the number of parameters is equal to 2*/ ){
         $v( 'Derek', 'Smith' );
     }
     else{ // method has no parameters
        $v();
     }
   }
   else{
       echo $k . ': ' . $v . '<br>'; // prints the properties
   }
}

1 个答案:

答案 0 :(得分:3)

您可以使用reflection

找到答案
$r = new ReflectionFunction($v);
$paramCount = $r->getNumberOfParameters();