What is the scope of require_once in PHP?

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.


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.