ternary operator - Conditionally assigning PHP values -
for common case of assigning value variable based on outcome of expression i'm fan of ternary operators:
$foo = $bar ? $a : b;
however, if $bar relatively expensive operation , want assign result of $bar $foo if result truthy, inefficient:
$foo = someclass::bigquery() ? someclass::bigquery() : new emptyset();
one option is:
$foo = ($result = someclass::bigquery()) ? $result : new emptyset();
but i'd rather not have $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 not style:
($foo = someclass::bigquery()) || ($foo = new emptyset());
so many options, non of them satisfactory. use, , missing obvious here?
php 5.3 introduced new syntax solve problem:
$x = expensive() ?: $default;
see main page:
since php 5.3, possible leave out middle part of ternary operator.
expressionexpr1 ?: expr3
returnsexpr1
ifexpr1
evaluatestrue
, ,expr3
otherwise.
Comments
Post a Comment