异常三元运算
我被要求执行三元运算符使用的操作:
$test='one';
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';
打印两个(使用 php 检查)。
我仍然不确定这的逻辑。请谁能告诉我这个的逻辑。
I was asked to perform this operation of ternary operator use:
$test='one';
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';
Which prints two (checked using php).
I am still not sure about the logic for this. Please, can anybody tell me the logic for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
嗯,那个?和 : 具有相同的优先级,因此 PHP 将从左到右依次解析每个位:
第一个
$test == 'one'
返回 true,因此第一个括号的值为 'one'。现在第二个三元数的计算如下:“one”为真(非空字符串),因此“two”是最终结果。
Well, the ? and : have equal precedence, so PHP will parse left to right evaluating each bit in turn:
First
$test == 'one'
returns true, so the first parens have value 'one'. Now the second ternary is evaluated like this:'one' is true (a non-empty string), so 'two' is the final result.
基本上,解释器从左到右评估该表达式,因此:
被解释
为 括号中的表达式评估为 true,因为“一”和“二”都不是 null/o/其他形式的 false。
因此,如果它看起来像:
它将打印三个。为了让它正常工作,你应该忘记组合三元运算符,并使用常规的 ifs/switch 来实现更复杂的逻辑,或者至少使用括号,以便解释器理解你的逻辑,而不是以标准 LTR 方式执行检查:
Basically interpreter evaluates this expression from left to right, so:
is interpreted as
And the expression in paratheses evaluates to true, since both 'one' and 'two' are not null/o/other form of false.
So if it would look like:
It would print three. To make it work okay, you should forget about combining ternary operators, and use regular ifs/switch for more complicated logic, or at least use the brackets, for the interpreter to understand your logic, and not perform checking in standard LTR way:
当你使用括号时它工作正常:
我不明白它 100% 但没有括号,对于解释器来说,语句必须如下所示:
第一个条件的结果似乎作为整个三元运算的结果返回。
It works correctly when you use brackets:
I don't understand it 100% but without brackets, to the interpreter, the statement must look like this:
the result of the first condition seems to be returned as the result of the whole ternary operation.
我认为它是这样评估的:
($test == 'one' ? 'one' : $test == 'two') 是非零/空,所以
如果你希望它工作, 'two' 是逻辑输出正确地写:
I think that it is evaluated like this:
($test == 'one' ? 'one' : $test == 'two') is non-zero/null, so 'two' is logical output
if you want it to work correctly, write:
PHP 的 文档 说:
如果在 false 语句两边加上括号,它会打印
one
:PHP'S documentation says:
If you put parenthesis around the false statement, it prints
one
:三元运算符按出现顺序执行,因此您确实拥有:
Ternary operators are executed in order of appearance so you really have:
嵌套三元运算太恶心了!上面的解释说明了原因。
基本上是这样的逻辑:
Nested ternary operations are gross! The above explanation shows why.
Basically this is the logic: