2

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

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.