使用三元运算符时可以通过引用传递吗? [英] Can you pass by reference while using the ternary operator?
问题描述
简单的问题,简单的代码.这有效:
Simple question, simple code. This works:
$x = &$_SESSION['foo'];
这不是:
$x = (isset($_SESSION['foo']))?&$_SESSION['foo']:false;
它抛出PHP Parse error: syntax error, unexpected '&'
.使用条件运算符时是否只能通过引用传递引用,为什么不呢?如果?
和&
之间存在空格,也会发生这种情况.
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 &
.
推荐答案
简单答案:否.如果要使用if/else,则必须走很长一段路.一次拥有一个引用,而下一次拥有一个值,这种情况也很罕见,并且可能会造成混淆.我会觉得这更直观,但是话又说回来,我当然不知道您的代码:
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.
这篇关于使用三元运算符时可以通过引用传递吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!