Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of require_once in PHP?

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!

like image 353
TMG Avatar asked Apr 21 '10 00:04

TMG


1 Answers

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.

like image 145
zombat Avatar answered Oct 06 '22 22:10

zombat