我有一个代码库,开发者决定使用 AND
和 OR
代替 &&
和 ||
。
我知道运算符优先级有所不同(&&
在 and
前面),但在给定的框架(具体来说是PrestaShop)中,这显然不是原因。
你们正在使用哪个版本?使用 and
比使用 &&
更易读吗?还是没有区别?
我有一个代码库,开发者决定使用 AND
和 OR
代替 &&
和 ||
。
我知道运算符优先级有所不同(&&
在 and
前面),但在给定的框架(具体来说是PrestaShop)中,这显然不是原因。
你们正在使用哪个版本?使用 and
比使用 &&
更易读吗?还是没有区别?
AND
和 OR
,最终你会被这样的东西绊倒:$this_one = true;
$that = false;
$truthiness = $this_one and $that;
希望你能猜出$truthiness
等于多少?
如果你猜测是false
,答错了!
$truthiness
的值为true
。为什么呢?因为=
的优先级高于and
。加上括号可以更清楚地显示隐含的顺序:
($truthiness = $this_one) and $that
&&
而不是and
,它将按预期工作并返回false
。=
具有更高的优先级。$truthiness = ($this_one and $that)
$foo and bar()
这样的东西,这是if语句的不错快捷方式。如果由于糟糕的文档或未阅读文档而导致意外行为成为不使用某物的原因,那么我们根本就不会谈论使用PHP。 - Altreus根据它的使用方式,可能需要甚至很方便。
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框架中我见过的每个实例一样。
if ($f = false or true) $f = true;
- 最终结果是 $f
变成了 true,因为整个表达式总体上是 true。 - Chris Browne$f
被赋值为false - 但条件评估为true,因此$f
被覆盖。如果条件评估为false,则无论如何$f
都不会被覆盖。 - ahouse101and
而不是 &&
,其中 and
仅在某些情况下按预期工作,而 &&
在所有情况下都按预期工作。 - ADTCand
的优先级低于 =
,因此你可以在条件赋值中使用它:
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
为了安全起见,我总是加括号并将比较分开。这样,我就不必依赖运算符优先级:
if(
((i==0) && (b==2))
||
((c==3) && !(f==5))
)
&& 和 and 的优先级不同(&& 的优先级高于 and),这在与三元运算符结合时容易引起混淆。例如:
$predA && $predB ? "foo" : "bar"
将返回一个字符串,而
$predA and $predB ? "foo" : "bar"
将返回一个布尔值。
7 = 0111
14 = 1110
------------
= 0110 == 6
另一个很好的例子是使用if
语句而不涉及=
赋值操作。
if (true || true && false); // is the same as:
if (true || (true && false)); // TRUE
并且
if (true || true AND false); // is the same as:
if ((true || true) && false); // FALSE
AND
的优先级较低,而 ||
的优先级较高。true, false, false
和 true, true, false
的情况下是不同的。
请参见 https://ideone.com/lsqovs,其中有一个详细的示例。这里有一个简单的计数器示例:
$a = true;
$b = true;
$c = $a & $b;
var_dump(true === $c);
输出:
bool(false)
我认为这种打字错误更容易导致隐蔽的问题(就像=
与==
一样),而且比adn
/ro
打字错误更不容易被注意到,后者会标记为语法错误。我也发现使用 and/or 更容易阅读。值得一提的是,大多数表达偏好的 PHP 框架(大多数没有)都指定了 and/or。我也从未遇到过一个真正的、非人为制造的情况,在这种情况下它会有所影响。
我想这是个品味问题,尽管(错误地)混淆它们可能会导致一些不良行为:
true && false || false; // returns false
true and false || false; // returns true
var_dump(true and false || false); // bool(false)
$a = true and false || false; var_dump($a); // bool(true)
$a === true
的原因是赋值运算符比任何逻辑运算符都具有优先级,这已经在其他答案中非常好地解释了。