For the very common case of assigning a value to a variable based on the outcome of an expression I'm a fan of ternary operators:
$foo = $bar ? $a : b;
However, if $bar is a relatively expensive operation and I want to assign the result of $bar to $foo if the result is truthy, this is inefficient:
$foo = SomeClass::bigQuery() ? SomeClass::bigQuery() : new EmptySet();
One option is:
$foo = ($result = SomeClass::bigQuery()) ? $result : new EmptySet();
But I'd rather not have the extra $result
sitting in memory.
The best option I've got is:
$foo = ($foo = SomeClass::bigQuery()) ? $foo : new EmptySet();
Or, without ternary operators:
if(!$foo = SomeClass::bigQuery()) $foo = new EmptySet();
Or, if program flow operators are not your style:
($foo = SomeClass::bigQuery()) || ($foo = new EmptySet());
So many options, non of them really satisfactory. Which would you use, and am I missing something really obvious here?