Search code examples
phperror-handlingundefined-variable

Is there a clean way to use undefined variables as optional parameters in PHP?


Is there any nice way to use (potentially) undefined Variables (like from external input) as optional Function parameters?

<?php
$a = 1;

function foo($a, $b=2){
    //do stuff
    echo $a, $b;
}

foo($a, $b); //notice $b is undefined, optional value does not get used.
//output: 1

//this is even worse as other erros are also suppressed
@foo($a, $b); //output: 1

//this also does not work since $b is now explicitly declared as "null" and therefore the default value does not get used
$b ??= null;
foo($a,$b); //output: 1

//very,very ugly hack, but working:
$r = new ReflectionFunction('foo');
$b = $r->getParameters()[1]->getDefaultValue(); //still would have to check if $b is already set
foo($a,$b); //output: 12

the only semi-useful method I can think of so far is to not defining the default value as parameter but inside the actual function and using "null" as intermediary like this:

<?php
function bar ($c, $d=null){
    $d ??= 4;
    echo $c,$d;
}

$c = 3
$d ??= null;
bar($c,$d); //output: 34

But using this I still have to check the parameter twice: Once if it is set before calling the function and once if it is null inside the function.

Is there any other nice solution?


Solution

  • Ideally you wouldn't pass $b in this scenario. I don't remember ever running into a situation where I didn't know if a variable existed and passed it to a function anyway:

    foo($a);
    

    But to do it you would need to determine how to call the function:

    isset($b) ? foo($a, $b) : foo($a);
    

    This is kind of hackish, but if you needed a reference anyway it will be created:

    function foo($a, &$b){
        $b = $b ?? 4;
        var_dump($b);
    }
    
    $a = 1;
    foo($a, $b);