Logical-Operators如何在三个布尔变量之间进行操作?

How are Logical-Operators operated among three boolean variates?

我现在是PHP的新手,对程序逻辑不甚了解,所以这段代码史诗让我很困惑。

返回给我的最终结果是"true false"。在我看来,结果应该都是假的,因为 "$b" 和 "$c" 具有不同的值,所以它们不能满足条件 "and".

另外,如果先将"$a"和"$b"作为一个组进行运算,则"$a或$b"的结果应该是"true",不等于$c要么。

非常感谢!

版本是PHP7

<?php
$a = true;
$b = true;
$c = false;

if($a or $b and $c)
echo 'true'." ";
else 
echo 'false';
?>

结果页:enter image description here

如有疑问,请使用括号使条件明确。这样以后就更容易理解代码了。

条件的顺序取决于运算符的优先级,如果相同则从左到右。

然而 PHP 实际上在处理条件时优化了条件。在 $c1 or $c2 的情况下,如果 $c1true$c2 的值无关紧要,因此不会被验证。结果只能是true$c1 and $c2 也是如此——如果 $c1 为假,则整体条件的结果只能是 false

因此 ($a or $b and $c)($a or ($b and $c)) 相同,您的预期结果使用 (($a or $b) and $c)

这是一个小脚本,您可以对其进行测试:

// a small function with some debug output
function createConditions(bool ...$values) {
    return function($callIndex) use ($values) {
        echo 'Call #', $callIndex, "\n";
        return $values[$callIndex - 1] ?? false;
    };
}
$c = createConditions(true, true, false);

if ($c(1) or $c(2) and $c(3)) {
    echo "Result: TRUE\n\n";
} else {
    echo "Result: FALSE\n\n";
}

if (($c(1) or $c(2)) and $c(3)) {
    echo "Result: TRUE\n\n";
} else {
    echo "Result: FALSE\n\n";
}

输出:

Call #1 
Result: TRUE 

Call #1 
Call #3 
Result: FALSE