PHP中带有布尔表达式的赋值:奇怪的行为 [英] Assignment in PHP with bool expression: strange behaviour

查看:78
本文介绍了PHP中带有布尔表达式的赋值:奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么$ x在此陈述中为真?

Why is $x true in this statment?

$x = true and false;

我遇到了一些变量问题,但是我可以将问题简化为原始的布尔值.

I've got the problem with some variables but I could reduce the problem to the primitive boolean values.

更新: 如您在答复中所见,效果与PHP中的运算符优先级有关.还有一个关于此问题中问题的很好的解释,我在该书中找不到之前的网络,因为我不知道自己对此有问题,也不知道'&&'/'||之间有区别和和"/或".

Update: As you see in the replies the effect has to do with the operator precedense in PHP. There is also a good explanation about the problem in this question, which I couldn't find in the net before since I didn't know that I have a problem with this and I didn't know that there is a difference between '&&'/'||' and 'and'/'or'.

推荐答案

经过一番搜索,我发现这是由

After some search I found out that this is caused by the operator precedence in PHP. The '=' operator is stronger than 'and'.

如果要获得预期的结果,则必须使用花括号:

If you want to get the expected result you have to use braces:

$x = (true and false); //correct: $x is false now!

不带大括号的表达式等于($x = true) and false;. $ x将获得真"值.之后,PHP解释器用$ x刚刚得到的值替换"此赋值.因此true and false;仍然存在.那什么也没做. 假"丢失并且不影响表达式.

Without braces the expression is equal to ($x = true) and false; . $x will get the 'true' value. After that the PHP interpreter 'replaces' this assignment with the value that $x has just got. So true and false; remains. And that does not do anything. 'false' is lost and didn't influence the expression.

请注意,如果您使用'&&',则不需要大括号.或"||"!它们比'='强,因此比'and'和'or'强.奇怪...

Be aware that the braces are NOT required if you use '&&' or '||'! They are stronger than '=' and thus stronger than 'and' and 'or'. Strange...

这与例如$x = 5 + 6;因为这里的"+"比"="更强,所以将首先对其进行解析.最后,它仅影响布尔运算符"and","or"和"xor".只有和他们在一起,您才需要提防.

This is different to e.g. $x = 5 + 6; since here '+' is stronger than '=' it will be resolved first. In the end it affects only the boolean operators 'and', 'or' and 'xor'. Only with them you have to watch out.

还请注意,这与其他语言(例如JavaScript或Java)相比有所不同.在这些语言中,您不需要括号,因为逻辑运算符比相等运算符强(运算符在Java中).

Note also that this is different compared to other languages like JavaScript or Java. In those languages you don't need the braces since the logical operators are stronger than the equal operator (Operators in JavaScript, Operators in Java).

这篇关于PHP中带有布尔表达式的赋值:奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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