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.
expression expr1 ?: expr3 returns expr1 if expr1 evaluates true, , expr3 otherwise.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -