6

require并且include有变化require_onceinclude_once。它们阻止脚本多次加载文件。

我想我可以放心地假设,因为这些函数存在,所以在某些情况下你需要require/include函数而不是require_once/函数include_once。但我无法想象这样的情况。那会是什么?

4

2 回答 2

9

最好的例子可能是给出输出时。例如,如果您有一段 HTML 片段可能在不同的页面上出现多次,您可以将它放入一个单独的文件中,并根据需要多次包含它。

此外,通常不需要使用require_onceor include_once。如果文件只会被调用一次(例如 in __autoload),那么简单函数的开销会更少,因为 PHP 不需要跟踪文件之前是否包含过。

于 2013-11-02T21:56:34.590 回答
1

One may want to use require_once instead of require if you want to have a variable or constant defined only once. This is helpful for making reusable classes in a very large code base that manages dependencies rapidly. Lets say I have a file A that needs a file B but I already include file C that included file B. Since file B was already included, the program does not have to evaluate that code again to properly evaluate file A. This is a case where you may want to include the file only once.

It helps with managing your dependencies

于 2015-02-23T05:52:00.377 回答