1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Great, it's the shortest way I've seen working so far. Also, thanks for the suggestion. \$\endgroup\$ – Max Korlaar Feb 1 '15 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.