PHP嵌套的条件运算符错误? [英] PHP nested conditional operator bug?

查看:63
本文介绍了PHP嵌套的条件运算符错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 
返回
true吗? ‘a’:
false吗? ‘b’:
‘c’;

这应该返回‘a’,但不是。而是返回 b。 PHP处理条件运算符不同部分的顺序是否存在错误?



我从它在哪里似乎可以正常工作。 p>

(当然,true和false是为了示例的目的。在真实代码中,它们分别是分别评估为true和false的语句。是的,我知道肯定)

解决方案


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


摘自 PHP手册非显而易见的三元行为。



三元运算符是从左到右求值的,因此,除非您将其添加到括号中,否则它不会像您期望的那样运行。但是,下面的方法会起作用,

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


   
                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)

解决方案

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"));

这篇关于PHP嵌套的条件运算符错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆