views:

90

answers:

1

I use the ternary operator quite often but I've not been able to find anything in the documentation about this and I've always wondered it.

The following is a possible example:

echo ($something->message ? $something->message : 'no message');

as you can see, if $something->message is correct, we return $something->message, but why write it twice? Is there a way to do something like:

echo ($something->message ? this : 'no message');

Now I'm not well versed in programming theory, so it's possible that there is a reason that the former cannot be referenced with something like "this" but why not? Would this not stream line the use of the ternary operator? For something like my example it's pretty useless, but let's say it's

echo (function(another_function($variable)) ? function(another_function($variable)) : 'false');

I'm unable to find any way to do this, so I'm assuming it's not possible, if I'm wrong please inform me, otherwise: why not? Why is this not possible, what's the technical reason, or is it just something that never happened? Should I be declaring it as a variable and then testing against that variable?

+17  A: 

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Source

For example

$used_value = function1() ?: $default_value;

Is the same as

$check_value = function1(); //doesn't re-evaluate function1()
if( $check_value ) {
    $used_value = $check_value;
} else {
    $used_value = $default_value;
}

Word for the wise

If your going to be depending on typecasting to TRUE it's important to understand what WILL typecast to TRUE and what won't. It's probably worth brushing up on PHP's type juggling and reading the type conversion tables. For example (bool)array() is FALSE.

Kendall Hopkins
Whoever submitted that patch is my hero. I was just reading that page and seemingly skipped straight over that part. Thanks, maybe I should upgrade then. I'll accept your answer when the time limit is up!
citricsquid
`echo ($something->message ? : 'no message');` in the case of the OP's first example.
Peter Ajtai
+1 Leave it to php to surprise you with an obscure implementation of the ternary operator of all things :) gotta love the incongruities..
Doug T.
@Doug T. It's not *that* obscure, http://en.wikipedia.org/wiki/%3F:#C_Variants
Kendall Hopkins
@Kendall wow... :) Well most of my colleagues get grouchy when they see a ternary operator. I'd *love* to have them try to figure out one of these ternary variants :)
Doug T.
The funny thing is that this was the result of the PHP 6 brainstorming about ifsetor() (see http://www.php.net/~derick/meeting-notes.html#ifsetor-as-replacement-for-foo-isset-foo-foo-something-else), and while it's a neat feature, it doesn't actually solve the original problem, since $_GET['foo'] ?: '' will still throw an notice if it's not set.
bluej100