How exactly is include/require resolved in PHP?

20 views Asked by At

I have a file include/vars.php, relative to the server root:

<?php

$SOME_VAR = "...";

and a file defining a function include/funcs.php:

<?php

require "vars.php";

function my_func() {
    echo(var_dump($SOME_VAR));
}

then a file endpoint.php supposed to call my_func:

<?php

require "include/funcs.php";

my_func();

I would expect this to output ... but I get the error

Undefined variable SOME_VAR in include/funcs.php

when I move the require inside the function, it works. But not when I add a require to endpoint.php:

// include/funcs.php
<?php

function my_func() {
    require "vars.php"; // works
    echo(var_dump($SOME_VAR));
}
// endpoint.php
<?php

require "include/vars.php"; // does not work
require "include/funcs.php";


my_func();

So how is the require statement actually resolved? I would expect when the imported file includes vars.php, the variables are also visible in the importing file. If not, I would have thought at least importing the variable first will make it visible to functions imported later on. However only importing the variable inside the function itself works.

Is this correct or am I doing something wrong? Maybe it has to do with the directory structure? How could I debug this?

0

There are 0 answers