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

问题描述

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

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



我从 p>

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

解决方案

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



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

  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)

解决方案

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嵌套的条件运算符错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:33