Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pass by reference while using the ternary operator?

Simple question, simple code. This works:

$x = &$_SESSION['foo'];

This does not:

$x = (isset($_SESSION['foo']))?&$_SESSION['foo']:false;

It throws PHP Parse error: syntax error, unexpected '&'. Is it just not possible to pass by reference while using the conditional operator, and why not? Also happens if there's a space between the ? and &.

like image 768
Andrew Avatar asked Aug 02 '10 16:08

Andrew


People also ask

Can we use ternary operator in while loop?

Ternary Operator Condition The condition can be any Java expression that evaluates to a boolean value, just like the expressions you can use inside an if - statement or while loop.

What are the three conditions in a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Why we should not use ternary operator?

They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.

Can you use functions in ternary operator?

Nope, you can only assign values when doing ternary operations, not execute functions.


2 Answers

In the very simply case, this expression, which is illegal;

$c = condition ? &$a : &$b; // Syntax error 

can be written like this:

$c = &${ condition ? 'a' : 'b' }; 

In your specific case, since you're not assigning by reference if the condition is false, a better option seems to be:

$x = isset($_SESSION['foo']) ? $x = &$_SESSION['foo'] : false; 
like image 182
jgivoni Avatar answered Sep 30 '22 04:09

jgivoni


Simple answer: no. You'll have to take the long way around with if/else. It would also be rare and possibly confusing to have a reference one time, and a value the next. I would find this more intuitive, but then again I don't know your code of course:

if(!isset($_SESSION['foo'])) $_SESSION['foo'] = false;
$x = &$_SESSION['foo'];

As to why: no idea, probably it has to with at which point the parser considers something to be an copy of value or creation of a reference, which in this way cannot be determined at the point of parsing.

like image 30
Wrikken Avatar answered Sep 30 '22 03:09

Wrikken