Can you pass by reference while using the ternary operator?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 11:54:11

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.

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;

Unfortunately, you can't.

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

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

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).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!