PHP如果执行

PHP if execution

在 PHP 中,如果您有以下代码,$b 是否会被计算,因为 $a 会导致 if 语句 return false?

$a = false;
$b = true;

if ($a && $b) {
  // more code here
}

此外,如果 $b 确实得到评估,是否会出现 if 语句的一部分可能无法评估的情况,因为处理器已经知道该值为 false?

逻辑表达式的计算在结果已知后立即停止.

如果 $a 为假,$b 将不会被评估,因为它不会改变 ($a && $b) 结果。

其结果是,如果 $b 的评估比 $a 的评估需要更多的资源,请从 $a 开始您的测试条件。

但请注意:

PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code. (Source php docs)

因此,如果 $a 为假,您不应该假设 $b 永远不会被评估,因为它可能会在未来发生变化(说 php 文档)。

&& 的计算在满足 false 条件后立即停止。

这些 (&&) 是短路运算符,因此如果第一个条件为真(在 OR 的情况下)或假(在 AND 的情况下),它们不会去检查第二个条件。

参考:http://php.net/manual/en/language.operators.logical.php


来自文档:

<?php

// --------------------
// foo() will never get called as those operators are short-circuit

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());