'AND'和'&&'作为运算符

我有一个代码库,开发人员决定使用ANDOR来代替&&||

我知道运算符的优先级有所不同( &&在之前and ),但是对于给定的框架(PrestaShop是精确的),显然不是一个理由。

你正在使用哪个版本? 是and不是更具可读性&& ? 还是没有区别?


如果你使用ANDOR ,你最终会被这样的事情绊倒:

$this = true;
$that = false;

$truthiness = $this and $that;

想猜测$truthiness等于什么?

如果你说false ... bzzzt,对不起,错!

上面的$truthiness true具有true值。 为什么? =具有比and更高的优先级。 添加圆括号以显示隐式顺序使得这个更清晰:

($truthiness = $this) and $that

如果您在第一个代码示例中使用&&而不是and ,则它将按预期工作,并且是false

正如在下面的评论中所讨论的那样,这也可以得到正确的值,因为括号具有比=更高的优先级:

$truthiness = ($this and $that)

根据使用方式的不同,这可能是必要的,甚至是方便的。 http://php.net/manual/en/language.operators.logical.php

// "||" has a greater precedence than "or"

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;

但在大多数情况下,它似乎更像是一种开发者的口味,就像我在@Sarfraz所提到的CodeIgniter框架中看到的每一次这样的事情。


由于and优先级低于=您可以在条件分配中使用它:

if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false
链接地址: http://www.djcxy.com/p/1717.html

上一篇: 'AND' vs '&&' as operator

下一篇: What does =& mean in PHP?