条件内包含/要求的 PHP 行为

2022-01-20 00:00:00 performance conditional include php

如果我将 includerequire 语句放在计算结果为 false 的条件中,PHP 解释器会完全跳过包含文件吗?还是会加载它以防万一?

If I place an include or require statement inside a conditional that evaluates to false, will the PHP interpreter skip the include file altogether, or will it load it just in case?

一个例子是:

if ($some_user_var) {
    require 'this.php';
} else {
    //do stuff
}

我在某处读到 require 将始终被解释器包含,而不管条件如何,但 include 不会.如果是这种情况,仅仅从 require 切换到 include 可能意味着由于减少了 I/O 和解析开销而可以免费加速.

I read somewhere that require will always be included by the interpreter regardless of the conditional, but include will not. If that's the case, just switching from require to include could mean a free speedup due to the reduced I/O and parsing overhead.

如果我运行像 eAccelerator 这样的预处理器可能会有所不同,但假设我没有.

It probably makes a difference if I'm running a preprocessor like eAccelerator, but let's assume I don't.

推荐答案

只有条件为真时才会包含.我不知道你从哪里读到的,但他们错了.

It will only be included if the condition is true. I don't know where you read otherwise, but they're wrong.

includerequire 的唯一区别是 include 如果失败会抛出警告,而 require 会抛出一个致命错误.

The only difference between include and require is that include will throw a warning if it fails, whereas require will throw a fatal error.

要确认这一点,请参阅 require 的 PHP 手册页.

To confirm this, see the PHP manual page for require.

(ps - 如果您正在执行条件包含,取决于原因,您可以考虑使用 include_once()require_once() 代替)

(ps - if you're doing conditional includes, depending on what the reaon is, you may consider using include_once() or require_once() instead)

相关文章