使用三元运算符时可以通过引用传递吗?
简单的问题,简单的代码。这有效:
$x = &$_SESSION['foo'];
这不起作用:
$x = (isset($_SESSION['foo']))?&$_SESSION['foo']:false;
它抛出 PHP 解析错误:语法错误,意外的“&”
。使用条件运算符时是否无法通过引用传递,为什么不呢?如果 ?
和 &
之间有空格,也会发生这种情况。
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 &
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在非常简单的情况下,这个表达式是非法的;
可以这样写:
在您的具体情况下,由于如果条件为假,您不会通过引用分配,所以更好的选择似乎是:
In the very simply case, this expression, which is illegal;
can be written like this:
In your specific case, since you're not assigning by reference if the condition is false, a better option seems to be:
简单的回答:不。你必须用 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:
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.
让我们试试:
所以,你看,它甚至没有解析。对于为什么不允许这样做,维基百科可能是正确的。
你可以用一个函数来解决这个问题:
给出:
a:
b:
Let's try:
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:
gives:
a:
b:
不幸的是,你不能。
Unfortunately, you can't.
对此错误报告的评论可能会阐明该问题:
http://bugs.php.net/bug.php?id=53117 。
本质上,尝试从三元运算符的结果分配引用的两个问题是:
$x = (expression)
不是引用分配,即使(expression)
是一个引用(实际上不是;参见第 1 点)。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:
$x = (expression)
is not a reference assignment, even if(expression)
is a reference (which it isn't; see point 1).