What is the scope of require_once in PHP?

喜夏-厌秋 提交于 2019-11-30 22:41:24

问题


Simple question: Is the scope of require_once global?

For example:

<?PHP

require_once('baz.php');

// do some stuff
foo ($bar);

function foo($bar) {
    require_once('baz.php');
    // do different stuff
}

?>

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:

Should require_once "some file.php" ; appear anywhere but the top of the file?

Thanks for your help!


回答1:


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.

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.

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.




回答2:


It does not. require_once's tracking applies to inside functions. However, the following scripts produce an error:

a.php

<?php
require_once('b.php');
function f() { require_once('b.php'); echo "inside function f;"; }
?>

b.php

<?php
f();
?>

because function f() is not pre-defined to b.php.




回答3:


To more specifically answer your question, the second time you call require_once on that file, it won't do anything, because it's already be included.

If your include has functions etc. in it, then you would have issues including it inside a function anyway, so scope is irrelevant. If it's just variables being defined or processed, then you can just use require instead of require_once if you want it to be included again, thereby redefining the variables in your scope.




回答4:


At least in PHP 7.3, require_once has global scope.
If it would not, both x.php and z.php should throw errors as y.php does:

a.php

<?php function a() { require_once 'b.php'; b(); }

b.php

<?php function b() { debug_print_backtrace(); }

x.php

<?php
require_once 'a.php';
a();
b();

-->

#0 c() called at [/var/www/b.php:2]  
#1 b() called at [/var/www/a.php:3]  
#0 c() called at [/var/www/a.php:4]  

y.php

<?php
require_once 'a.php';
b();

--> Fatal error: Uncaught Error: Call to undefined function b() in /var/www/y.php on line 3

z.php

<?php
require_once 'a.php';
require_once 'b.php';
b();

-->

#0 b() called at [/var/www/z.php:4]


来源:https://stackoverflow.com/questions/2679602/what-is-the-scope-of-require-once-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!