“AND"与“&&"作为运营商 [英] 'AND' vs '&&' as operator
问题描述
我有一个代码库,其中开发人员决定使用 AND
和 OR
而不是 &&
和 ||代码>.
I have a codebase where developers decided to use AND
and OR
instead of &&
and ||
.
我知道运算符的优先级存在差异(&&
在 and
之前),但是对于给定的框架(PrestaShop 准确地说)这显然不是原因.
I know that there is a difference in operators' precedence (&&
goes before and
), but with the given framework (PrestaShop to be precise) it is clearly not a reason.
你用的是哪个版本?and
是否比 &&
更具可读性?还是没有区别?
Which version are you using? Is and
more readable than &&
? Or is there no difference?
推荐答案
如果你使用 AND
和 OR
,你最终会被这样的事情绊倒:
If you use AND
and OR
, you'll eventually get tripped up by something like this:
$this_one = true;
$that = false;
$truthiness = $this_one and $that;
想猜猜 $truthiness
等于什么?
如果你说false
... bzzzt,对不起,错了!
If you said false
... bzzzt, sorry, wrong!
$truthiness
上面的值是 true
.为什么?=
具有比 更高的优先级 和
.添加括号以显示隐式顺序使这一点更加清晰:
$truthiness
above has the value true
. Why? =
has a higher precedence than and
. The addition of parentheses to show the implicit order makes this clearer:
($truthiness = $this_one) and $that
如果您在第一个代码示例中使用 &&
而不是 and
,它会按预期工作并且是 false
.
If you used &&
instead of and
in the first code example, it would work as expected and be false
.
正如在下面的评论中所讨论的,这也适用于获得正确的值,因为括号的优先级高于 =
:
As discussed in the comments below, this also works to get the correct value, as parentheses have higher precedence than =
:
$truthiness = ($this_one and $that)
这篇关于“AND"与“&&"作为运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!