[英]PHP - and / or keywords
&&
与“ and”相同,并且||
与PHP中的“或”相同?
我已经进行了一些测试,看来它们的行为相同。 有什么区别吗?
如果不是,是否还有其他具有单词等效功能的PHP标志,您认为它使代码更易于阅读吗?
and
和or
具有更高的优先级低于&&
和||
。 更确切地说&&
和||
and
和or
优先级高于赋值运算符( =
)。
http://www.php.net/manual/zh/language.operators.precedence.php
通常不会产生任何变化,但是在某些情况下,不知道该变化会导致某些意外行为。 在此处查看示例:
让我困扰的是:
echo (false and false ? true : true);
// (empty/false)
您可能会猜测只有可能的输出为“ 1”(真),因为没有任何情况下可能会输出“假” ... ...但是它将是“”(假)。
在这种情况下,使用&&作为运算符至少可以满足我的期望:
echo (false && false ? true : true);
// 1
因此,在某些情况下,用法很重要。
区别在于优先级 。 但不仅彼此相比!
在大多数情况下,您不会介意的,但是在某些特定情况下,您必须退后一步来了解大局。 以这个为例:
// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;
// The constant true is assigned to $h before the "and" operation occurs
// Acts like: (($h = true) and false)
$h = true and false;
var_dump($g, $h);
这将分别产生:
bool(false)
bool(true)
换句话说, &&
具有比=
更高的优先级, =
优先级高于and
,如http://php.net/manual/en/language.operators.precedence.php中所述 。 (在其他答案中也提到过,但我认为值得详细说明,因为滥用会导致逻辑错误)
希望对您有帮助。 您可以在http://php.net/manual/en/language.operators.logical.php中找到更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.