简体   繁体   English

三元运算符串联

[英]Ternary operator concatenation

Why does 为什么

1 == 1 ? 'green' : 1 < 0 ? 'red' : 'yellow'

return red in PHP? 在PHP中返回red

I come from Java and Javascript, where this expression returns green . 我来自Java和Javascript,该表达式返回green

Simple fiddle to show it: https://jsfiddle.net/yt0e8t93/ 简单的小提琴来显示它: https : //jsfiddle.net/yt0e8t93/

C, C++, Java, and Javascript will evaluate this as C,C ++,Java和Javascript会将其评估为

1 == 1 ? 'green' : (1 < 0 ? 'red' : 'yellow')

due to the associativity of the ternary conditional operator being from right to left in all those languages. 由于在所有这些语言中三元条件运算符的关联性是从右到左。 (This goes way back to before the if statement was even conceived). (这可以追溯到甚至想到if语句之前)。

But the PHP guys wanted to be different. 但是PHP的人希望与众不同。 In PHP, your expression is evaluated as 在PHP中,您的表达式被评估为

(1 == 1 ? 'green' : 1 < 0) ? 'red' : 'yellow'

This simplifies to 'green' ? 'red' : 'yellow' 这简化为'green' ? 'red' : 'yellow' 'green' ? 'red' : 'yellow' which in turn is 'red' as 'green' is truthy. 'green' ? 'red' : 'yellow' ,而又将'red''green'是真实的。 If you want it the old-fashioned way then use the parentheses as above. 如果您希望使用老式的方法,请使用上面的括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM