PHP 嵌套条件运算符错误?
return true ? 'a' : false ? 'b' : 'c';
这应该返回“a”,但事实并非如此。它返回“b”。 PHP 处理条件运算符不同部分的顺序是否存在错误?
我从 在这种情况下是否有多个条件运算符得到了这个想法一个好主意? 它似乎工作正常。
(当然,true 和 false 是为了示例的目的。在实际代码中,它们分别是评估为 true 和 false 的语句。是的,我肯定知道)
return true ? 'a' : false ? 'b' : 'c';
This should return 'a', but it doesn't. It returns 'b' instead. Is there a bug in PHP's order of handling the different parts of the conditional operators?
I got the idea from Are multiple conditional operators in this situation a good idea? where it does seem to work correctly.
(the true and false are for the purpose of the example, of course. in the real code they are statements that evaluate to true and false respectively. yes, i know that for sure)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 PHP 手册 下的“Non -明显的三元行为”。
三元运算符是从左到右计算的,因此除非您添加大括号,否则它的行为不会如您所期望的那样。不过,以下内容可以工作,
From the PHP Manual under "Non-obvious Ternary Behaviour".
Ternary operators are evaluated left to right, so unless you add it the braces it doesn't behave as you expect. The following would work though,
怀疑它正在评估
(true ? 'a' : false)
作为第二个三元运算符的输入,并将 'a' 解释为 true。尝试适当地包围。Suspect it's evaluating
(true ? 'a' : false)
as the input to the second ternary operator and interpreting 'a' as true. Try bracketing appropriately.操作顺序:
order of operations:
让我用向我解释的方式来解释。但你必须注意括号中的内容才能理解发生了什么。
PHP
下面的 PHP 代码
相当于:
另一种语言
下面的代码
相当于:
Let me explain in same way it was explained to me. But you have to pay attention in parenthesis to understand what is happening.
The PHP
The PHP code below
Is equivalent to:
Another languages
The code below
Is equivalent to: