Problem
I have the following piece of code in my project, and that a few times:
$this->uniqueSessionKey = $settings->get('uniqueSessionKey') ? $settings->get('uniqueSessionKey') : $_SERVER['HTTP_USER_AGENT'] . time();
I was wondering if there’s a better way of writing this, especially the part where it checks if $settings->get(...)
is not false and then uses the previously checked value. As it uses a database connection it’s probably not very efficient checking for the same thing twice.
Is there a better way of writing this? I’m already using the shortest if-else that I’m aware of.
If it’s not possible, I will put the $settings->get(...)
in a variable anyway, and then check if it’s false. I’ve tried using ||
but that returned false (?) so I probably did that wrong.
Note that I don’t want to check it for multiple values, so I don’t need to use for
etc.
Solution
Since PHP 5.3 you can use the shortcut $a = $b? : $c
:
$this->uniqueSessionKey = $settings->get('uniqueSessionKey') ? : $_SERVER['HTTP_USER_AGENT'] . time();
—
Just a note: you can not use this if you want check if the var $a is set. In this case you must use the original form: $a = isset($b)? $b : $c;
Otherwise, you can write a custom function in this way:
function getIfSet(&$a, $default = null) {
return isset($a)? $a : $default;
}
$a = getIfSet($b,$c);
Passing var by reference (&$a
) avoid the PHP notice if $a is not set.