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 &
.
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.
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.
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.
Nope, you can only assign values when doing ternary operations, not execute functions.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With