Is there a way to set the scope of require_once() explicitly to global?

前端 未结 7 1575
梦谈多话
梦谈多话 2021-02-19 11:47

I\'m looking for a way to set the scope of require_once() to the global scope, when require_once() is used inside a function. Something like the follow

7条回答
  •  耶瑟儿~
    2021-02-19 12:28

    As the scope is explicitly defined where you use require and the like, you would need to specify what to do with the variables inside the scope of the function:

    function includeFooFile() {
        require_once("foo.php"); // scope of "foo.php" will be the function scope
    
        foreach (get_defined_vars() as $k => $v)
        {
            $GLOBALS[$k] = &$v;
        }
    }
    

    This example takes care of both, variables and references which might be what you're looking for. Demo. Please note that require_once would only work once and would only define the variables once.

提交回复
热议问题