I have the this method:
public function search($searchKey=null, $summary=null, $title=null, $authors=null, $paginationPage=0) {
...
}
And I'm trying to retrieve all parameters with this:
$Class = new Search();
// Get parameters
$ReflectionMethod = new \ReflectionMethod($Class, "search");
try {
foreach($ReflectionMethod->getParameters() AS $Parameter) {
if(array_key_exists($Parameter->name, $this->params)) {
$parameters[$Parameter->name] = $this->params[$Parameter->name];
} elseif($Parameter->isDefaultValueAvailable()) {
$paramaters[$Parameter->name] = $Parameter->getDefaultValue();
} else {
...
}
} catch(\Exception $e) {
...
}
// Call function
return call_user_func_array(array($Class, "search"), $parameters);
My $this->params
has this content:
array
'paginationPage' => int 2
'id' => int 30
'searchKey' => string 'test' (length=4)
Because $summary, $title and $authors are not present, they will get their default value which is null
. When assigning a null value to an argument, it will be skipped which results in a $parameters array that looks like this:
array
'searchKey' => string 'test' (length=4)
'paginationPage' => int 2
Which result in a method call like:
public function search('test', 2, null, null, 0) {
...
}
While it should be:
public function search('test', null, null, null, 2) {
...
}
Hopefully you see the problem. How can I make sure those null values are also put into my $parameters
array. Adding an invalid value is not possible, because it is user input, so that can be basically everything.
Edit
In the example above the method search
is hardcoded. But one of the simplified things is that search
is actually a variable and because of that search
can be anything. This means that I don't know what the parameters of the method are and I can't predefine them before the foreach loop. The solution of predefining the parameters is actually exactly what this code should be doing.
How about pre-initializing $parameters
before entering the foreach
loop:
$parameters = array(
$searchKey => null,
$summary => null,
$title => null,
$authors => null,
$paginationPage => 0
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With