require
并且include
有变化require_once
和include_once
。它们阻止脚本多次加载文件。
我想我可以放心地假设,因为这些函数存在,所以在某些情况下你需要require
/include
函数而不是require_once
/函数include_once
。但我无法想象这样的情况。那会是什么?
最好的例子可能是给出输出时。例如,如果您有一段 HTML 片段可能在不同的页面上出现多次,您可以将它放入一个单独的文件中,并根据需要多次包含它。
此外,通常不需要使用require_once
or include_once
。如果文件只会被调用一次(例如 in __autoload
),那么简单函数的开销会更少,因为 PHP 不需要跟踪文件之前是否包含过。
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