Search code examples
phpvariablesdefault-value

PHP variable "default value"


I want to get a value from the session, but use a default if it is not defined. And ofcourse I want to circumvent the PHP notice.

You can write a function that does this

function get(&$var, $default){
    if(isset($var)) return $var;
    return $default;
}

echo get($foo, "bar\n");
$foobar = "foobar";
echo get($foobar, "ERROR");

Example in action

Is there a way to do this without defining this function in every file?


Solution

  • From PHP 7, you can now use the null coalescing operator :

    $var ?? $default
    

    that does exactly like your function