Ternary operator not working with reference variables in PHP [closed]

吃可爱长大的小学妹 提交于 2019-12-23 18:17:03

问题


Why isn't this working?

$a = 'FOO';

$foo = $a ? &$a : 'whatever'; // <- error here

echo $foo;

I get a parse error :|


回答1:


If you want to assign a reference using a ternary statement, then you need this clumsy workaround:

 list($foo) = $a ? array(&$a) : array('whatever');

However, as said in the other answers, this seldomly saves memory.




回答2:


Although you tagged your question if-statement, that's not an if statement, it's a ternary conditional expression. I've retagged it accordingly.

Now, the reason why it doesn't work is because assigning by reference is different from assigning normal value expressions in PHP. You can't use references with the ?: operator in the same way you can't do return &$foo; in a function. See these manual pages about PHP references for more:

  • What References Do
  • Returning References

If you use an actual if statement, it'll work:

if ($a)
    $foo = &$a;
else
    $foo = 'whatever';

But why you'd want to use references like this is beyond me (unless this is PHP 4, and even then you shouldn't be using PHP 4 anymore).




回答3:


Try this:

$a ? $foo = &$a : $foo = 'whatever';


来源:https://stackoverflow.com/questions/5931680/ternary-operator-not-working-with-reference-variables-in-php

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