开发者

PHP reflection and invokeArgs(): forcing a parameter to use its default value

I need to call a function using the Reflection API. The function has optional parameters, and I need to invoke it providing just some of them.

For example, I have this function:

public function doSomething($firstParam, $secondParam = "default", $thirdParam = "default)

And I'm using invokeArgs() to invoke doSomething(), passing an array of values representing the arguments omitting to set a value to 开发者_高级运维the optional $secondParam:

$parameters = array("firstParam"=>"value", "thirdParam"=>"thirdValue");
$reflectedDoSomething->invokeArgs($instance, $parameters);

What happens here is that invokeArgs() invokes the method setting its parameters in a row, without skipping the $secondParam, that now is valued "thirdValue" and omitting the $thirdParam. And that's logically correct. The method is invoked like doSomething("value", "thirdValue").

What I'd like to do here is to force the $secondParam to use its default value. Setting "secondParam" => null in the $parameters array is not a solution because null is a value.

Is it possibile using Reflection?

Thanks


See the first comment on the docs for invokeArgs().

So, just run the params through a simple algorithm (you could create a function for wrapping this if you wanted to):

$reflection = new ReflectionMethod($obj, $method); 

$pass = array(); 
foreach($reflection->getParameters() as $param) { 
   /* @var $param ReflectionParameter */ 
   if(isset($args[$param->getName()])) { 
       $pass[] = $args[$param->getName()]; 
   } else { 
       $pass[] = $param->getDefaultValue(); 
   } 
} 
$reflection->invokeArgs($obj, $pass);


How about not setting the associative name secondParam, but rather putting a null as a second second parameter.

$parameters = array("firstParam"=>"value", null, "thirdParam"=>"thirdValue");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜