PHP中require_once的范围是什么? [英] What is the scope of require_once in PHP?
问题描述
一个简单的问题:require_once
的范围是全局的吗?
Simple question: Is the scope of require_once
global?
例如:
<?PHP
require_once('baz.php');
// do some stuff
foo ($bar);
function foo($bar) {
require_once('baz.php');
// do different stuff
}
?>
调用foo时,会重新解析baz.php吗?还是依赖于主php文件中已经需要的文件(类似于对于相同的include文件连续两次调用require_once )?
When foo is called, does it re-parse baz.php? Or does it rely on the already required file from the main php file (analagous to calling require_once twice consecutively for the same include file)?
我以前见过这个线程,但是并没有完全回答这个问题:
I saw this thread before, but it didn't quite answer the question:
应该require_once某些file.php" ;出现在文件顶部以外的任何地方?
感谢您的帮助!
推荐答案
require_once()
基本上依赖于物理文件来确定是否包含该文件.因此,要调用require_once()
的上下文并不多,而是以前是否需要该物理文件.
require_once()
basically relies on the physical file to determine whether or not it's been included. So it's not so much the context that you're calling require_once()
in, it's whether or not that physical file has previously been required.
在上面的代码中,您的foo()
函数将不会重新解析baz.php
,因为它将与先前在顶部包含的文件相同.
In your code above, your foo()
function would not re-parse baz.php
, since it is going to be the same file as was previously included at the top.
但是,根据将其包含在foo()
内还是将其包含在顶部,您将获得不同的结果,因为当require_once()
成功执行时,作用域将适用.
However, you will get different results based on whether you included it inside foo()
, or included it at the top, as the scoping will apply when require_once()
does succeed.
这篇关于PHP中require_once的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!