PHP嵌套的条件运算符错误?(PHP nested conditional operator bug?)

编程入门 行业动态 更新时间:2024-10-19 11:37:13
PHP嵌套的条件运算符错误?(PHP nested conditional operator bug?) return true ? 'a' : false ? 'b' : 'c';

这应该返回'a',但它不会。 它返回'b'。 PHP处理条件运算符的不同部分时是否存在错误?

我从这种情况下得到了多个条件运算符的想法是一个好主意? 它看起来工作正常。

(真假是为了这个例子的目的,当然,在真实的代码中,它们是分别评估为真和假的语句,是的,我知道肯定)

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)

最满意答案

建议您避免“堆叠”三元表达式。 在单个语句中使用多个三元运算符时,PHP的行为并不明显

从“非明显的三元行为”下的PHP手册 。

三元运算符从左到右进行评估,所以除非你添加大括号,否则它的行为并不像你期望的那样。 以下工作虽然,

return (true ? "a" : (false ? "b" : "c"));

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious

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,

return (true ? "a" : (false ? "b" : "c"));

更多推荐

本文发布于:2023-04-28 00:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329708.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   运算符   条件   错误   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!