如何评估条件中的所有表达式?

时间:2013-04-30 01:25:08

标签: php lazy-evaluation

我知道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中进行评估,如果没有,在上面的例子中获得所需结果的最佳/最快方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用bitwise AND(单&符号:&

$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";
}

打印:

  

Apple很好。

     

香蕉很糟糕。

     

樱桃很好。

示例:http://sandbox.onlinephpfunctions.com/code/07092a9d6636ae8ddafce024d7cc74643e311e9c

答案 1 :(得分: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!
*/