包含 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 希望在当前路径 /api/.

中包含 config.php

此外,如果您无论如何都要调用 getDatabase(),为什么还要声明 global $database