1

我知道 PHP 使用惰性求值/短路运算符。但是假设我想评估条件中的所有表达式,例如:

$a = "Apple";
$b = "Banana";
$c = "Cherry";

function check($fruit) {
    if ($fruit != "Banana") {
        echo "$fruit is good.\n";
        return true;
    } else {
        echo "$fruit is bad.\n";
        return false;
    }
}

if (check($a) && check($b) && check($c)) {
    echo "Yummy!\n";
}

由于惰性求值,这只会输出:

Apple is good.
Banana is bad.

而不是所需的输出:

Apple is good.
Banana is bad.
Cherry is good.

例如,这在表单验证中很有用。

所以我的问题是:有没有办法强制条件中的所有表达式在 PHP 中进行评估,如果没有,在上面的示例中获得所需结果的最佳/最快方法是什么?

4

2 回答 2

1

You can use bitwise AND (single ampersand: &)

$a = "Apple";
$b = "Banana";
$c = "Cherry";

function check($fruit) {
    echo ($fruit != "Banana") ? "$fruit is good.\n" : "$fruit is bad.\n";
}

if (check($a) & check($b) & check($c)) {
    echo "Yummy!\n";
}

Prints:

Apple is good.

Banana is bad.

Cherry is good.

Example: http://sandbox.onlinephpfunctions.com/code/07092a9d6636ae8ddafce024d7cc74643e311e9c

于 2013-04-30T01:33:03.037 回答
0
function check($fruit) {
    echo ($fruit != "Banana") ? "$fruit is good.\n" : "$fruit is bad.\n";
    return $fruit != "Banana";
}


$a = "Apple";
$b = "Banana";
$c = "Cherry";
if (check($a) & check($b) & check($c)) {
    echo "Yummy!\n";
}


/*
Apple is good.
Banana is bad.
Cherry is good.
*/


$a = "Apple";
$b = "apple";
$c = "Cherry";
if (check($a) & check($b) & check($c)) {
    echo "Yummy!\n";
}


/*
Apple is good.
apple is good.
Cherry is good.
Yummy!
*/
于 2013-04-30T01:50:43.100 回答