PHP if()不返回true也不调用所有元素

时间:2015-08-17 10:57:08

标签: php

我有以下部分代码:

if (($product->uploadable_files != $files_count || $product->text_fields != $text_count) && !count($this->errors) && !$product->update())
        $this->errors[] = Tools::displayError('An error occurred while updating the custom configuration.');

为什么(我完全失去了atm)它不会拨打Tools::displayError也不会$product->update()

最后一个应该被称为。事实并非如此。

3 个答案:

答案 0 :(得分:5)

这可能意味着它甚至没有达到这一点。您可以将if语句分为三组:

1st:$product->uploadable_files != $files_count || $product->text_fields != $text_count

第二名:!count($this->errors)

第3名:!$product->update()

如果其中一个组为假,则整个条件将为假。如果1st是假的,它甚至不会达到第2和第3。如果第二个是假的,它就不会达到第三个。

此外,count永远不会返回false。您可能正在检查$this->errors是否为空,因此请使用empty($this->errors)

答案 1 :(得分:1)

扩展treegarden的答案, 如果处理不正确,count()可以评估为真。

var_dump(count([]));            # 0
var_dump(count([]) == false);   # true
var_dump(count([]) === false);  # false

Count返回第一个参数中的元素数。如果参数数组或对象实现了Countable接口,则 1将返回。有一个例外,如果array_or_countable为NULL,则返回0。

而是使用empty()

var_dump(!empty([])); # false

答案 2 :(得分:-1)

&安培;&安培;检查两者是否都是真的。如果第一个是假的,它会在那里结束,不会去其他任何地方,正如手册所说的那样是短路。同样适用于||。

http://php.net/manual/en/language.operators.logical.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());

// --------------------
// "||" 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;

var_dump($e, $f);

// --------------------
// "&&" has a greater precedence than "and"

// 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 and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;

var_dump($g, $h);
?>