PHP 处理 IF 语句中的多个子句

PHP handling multiple clauses in an IF statement

我有一个 php 代码可以执行此操作:

if (file_get_contents($businessData['header_image'],0,null,0,1) !== false) {
    $headerBackingImage = $businessData['header_image'];
    }
else {
    $headerBackingImage = "default_image_url.jpg";
}

目的是确定企业在定义的位置是否有有效的图像文件,然后在网页中使用该文件 URL。 $businessData 是数据库输出的数组。

我发现一些数据库行的 $businessData['header_image'] 值为空,这会导致警告:

PHP Warning: file_get_contents(): Filename cannot be empty

很明显,上述语句的前提是检查 $businessData['header_image'] 是否为空。使用 PHP empty() 函数轻松完成。

可以将其构造如下:

if (!empty($var)){
    if (file_get_contents($var)){
    ///file exists!
    }
else {
    ///file does not exist, use default.
    }
}
else {
        ///file does not exist, use default.
        }

但这意味着在 IF EMPTY 检查的内部和外部重复 else 子句。

我的问题

所以 - 这个布局如何维护单个 IF{...} 语句而不需要重复 ELSE{...} 子句:

if (!empty($businessData['header_image']) && file_get_contents($businessData['header_image'],0,null,0,1) !== false){ ... }

那么,如果第一个条件 return 为 FALSE,PHP 是否还要检查 IF 语句中的第二个条件?

上面的解决方案是否仍然是 return 警告,因为即使在将第一个 --empty()-- 函数评估为 FALSE 之后,PHP 仍然运行 file_get_contents 函数?

我从 php.net 和其他地方读到的关于这个的东西似乎只评估 IF 条件作为单个 return 块,如括号 return 之间的整个块s TRUE 或 FALSE 而不是 PHP 如何处理 IF 条件的每个子部分 return 分别为 TRUE 或 FALSE。

So, Does PHP bother checking the second condition in the IF statement if the first condition returns FALSE?

这里不,如果 AND 语句的第一部分是 flase PHP 不关心第二部分。您可以在此处轻松查看:

<?php

    function func() { echo "HERE!";}

    if(false && func()) {
        echo "yes";
    } else {
        echo "no";
    }

?>

输出:

no

如您所见,您没有得到输出:HERE!。但是,如果将 false 更改为 true,您将得到:HERE!no,因为调用了函数,因为第一部分为 true。

编辑:

如果你想准确地接受它,这叫做:短路评估

您可以在此处的手册中看到: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());

嗯,这种行为是可能的,因为 PHP 是基于 C 的。在 C 中你有短路,这在那里非常有用。

条件是从左到右解析的,如果没有必要则不会像您建议的代码那样执行。需要理解的是,如果第一部分为假,则整个块都是假的,因此整个块也返回假。