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.

asked Feb 1, 2015 at 17:09
\$\endgroup\$

1 Answer 1

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.

answered Feb 1, 2015 at 18:03
\$\endgroup\$
1
  • \$\begingroup\$ Great, it's the shortest way I've seen working so far. Also, thanks for the suggestion. \$\endgroup\$ Commented Feb 1, 2015 at 19:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.