Probably this is a limitation of PHP, but is it possible somehow, to call a function – and enforcing the ‘default’ value of an optional parameter – even if in the function call, the optional parameter is given (and == null)?
Maybe it’s easier to show what I mean:
<?php
function funcWithOptParam($param1, $param2 = 'optional') {
print_r('param2: ' . $param2);
}
funcWithOptParam('something'); // this is the behaviour I want to reproduce
// this will result in 'param2: optional'
funcWithOptParam('something', null); // i want $param2 to be 'optional', not null
// this will result in 'param2: ' instead of 'param2: optional'
?>
Now, the easiest answer to this is “dont write null then” – but in my special case, I get a parameter array for a function call, and only can do this:
<?php
funcWithOptParam($param[0], $param[1]);
?>
So even if $param[1] is null, the null will overwrite the default value of the optional parameter
I only see one solution to this – to skip the optional parameters, and do it like this:
<?php
function funcWithOptParam($something, $notOptional) {
if($notOptional === null) {
$notOptional = 'defaultvalue';
}
...
}
?>
But I would like to know if there’s another solution to this. Is there a ‘real’ null value in PHP? That really translates into ‘nothing’? Something like undefined in js?
Why not pass the whole array as the function argument?
You simply call it this way:
And handle it like so:
This approach gives you the possibility to pass only the arguments you want to specify and have default values in the ones you don’t want to specify. As a bonus you don’t have to worry about the order of the arguments.