views:

58

answers:

3

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

+4  A: 

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.

Wrikken
+2  A: 

Unfortunately, you can't.

$x=false;
if (isset($_SESSION['foo']))
   $x=&$_SESSION['foo'];
stillstanding
+1  A: 
Artefacto