php - Return statement shorthand syntax -
this question has answer here:
i new php developing far have been able whatever want. came across strange syntax of writing return statement:
public static function return_taxonomy_field_value( $value ) { return (! empty(self::$settings['tax_value']) ) ? self::$settings['tax_value'] : $value; }
i return()
, !empty()
after has ?
, that's lost. appreciated! guys
this ternary operator, short version of if
statement.
this:
$a = $test ? $b : $c;
is same as:
if($test) { $a=$b; } else { $a=$c; }
so example equivalent to:
if(! empty(self::$settings['tax_value']) { return self::$settings['tax_value']; } else { return $value; }
you can find more info here, tips precautions when using ternary operators.
important note difference other languages
since question marked duplicate of question deals ternary operator in objective-c, feel difference needs addressed.
the ternary operator in php has different associativity 1 in c language (and others far know). illustrate this, consider following example:
$val = "b"; $choice = ( ($val == "a") ? 1 : ($val == "b") ? 2 : ($val == "c") ? 3 : 0 ); echo $choice;
the result of code (in php) 3
, though seem 2
should correct answer. due weird associativity implementation threats upper expression as:
( ( ( ($val=="a") ? 1 : ($val=="b") ) ? 2 : ) ($val=="c") ? 3 : 0 ) ▲ ▲ ▲ ▲ | | | | \ \_____________________________/ / \_______________________________________/
Comments
Post a Comment