这应该返回'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"));更多推荐
发布评论