Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 &.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
316 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...