简体   繁体   中英

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

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.

Let's try:

$x =& true?$y:$x;
Parse error: syntax error, unexpected '?', expecting T_PAAMAYIM_NEKUDOTAYIM in...
$x = true?&$y:&$x;
Parse error: syntax error, unexpected '&' in...

So, you see, it doesn't even parse. Wikken is probably right as to why it's not allowed.

You can get around this with a function:

function &ternaryRef($cond, &$iftrue, &$iffalse=NULL) {
    if ($cond)
        return $iftrue;
    else
        return $iffalse;
}

$x = 4;
$a = &ternaryRef(true, $x);
xdebug_debug_zval('a');
$b = &ternaryRef(false, $x);
xdebug_debug_zval('b');

gives:

a:

(refcount=2, is_ref=1),int 4
b:
 (refcount=1, is_ref=0) ,null \n

Unfortunately, you can't.

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

The commentary on this bug report might shed some light on the issue:
http://bugs.php.net/bug.php?id=53117 .

In essence, the two problems with trying to assign a reference from the result of a ternary operator are:

  1. Expressions can't yield references, and
  2. $x = (expression) is not a reference assignment, even if (expression) is a reference (which it isn't; see point 1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM