包含 PHP 文件的位置会影响全局变量范围


Location of Including PHP File Affects Global Variable Scope

看来我的包含文件的位置会影响包含文件内的全局变量。这很复杂。见下文:


/config.php

<?php
    $domain = 'localhost';
    $database = 'db';
?>

/functions.php

<?php
    require_once("config.php");
    function getDatabase() {
        global $database;
        return $database;
    }
?>

/endpoint.php

<?php
    require_once($_SERVER['DOCUMENT_ROOT']."/functions.php");
    print(getDatabase());
?>

/api/endpoint.php

<?php
    require_once($_SERVER['DOCUMENT_ROOT']."/functions.php");
    print(getDatabase());
?>

当我导航到/endpoint.php时,db被打印出来。当我导航到/api/endpoint.php时,没有任何打印。有人可以解释一下这种行为吗?

顺便说一句:我正在使用XAMPP 5.5.19和PHP 5.5

这是因为在第二种情况下,functions.php希望从当前路径中包含 config.php /api/

另外,如果您无论如何都要打电话给getDatabase(),为什么要global $database声明?