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

前端 未结 7 1555
梦谈多话
梦谈多话 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:31

    You can use this hacky function I wrote:

    /**
     * Extracts all global variables as references and includes the file.
     * Useful for including legacy plugins.
     *
     * @param string $__filename__ File to include
     * @param array  $__vars__     Extra variables to extract into local scope
     * @throws Exception
     * @return void
     */
    function GlobalInclude($__filename__, &$__vars__ = null) {
        if(!is_file($__filename__)) throw new Exception('File ' . $__filename__ . ' does not exist');
        extract($GLOBALS, EXTR_REFS | EXTR_SKIP);
        if($__vars__ !== null) extract($__vars__, EXTR_REFS);
        unset($__vars__);
        include $__filename__;
        unset($__filename__);
        foreach(array_diff_key(get_defined_vars(), $GLOBALS) as $key => $val) {
            $GLOBALS[$key] = $val;
        }
    }
    

    It moves any newly defined vars back into global space when the include file returns. There's a caveat that if the included file includes another file, it won't be able to access any variables defined in the parent file via $GLOBALS because they haven't been globalized yet.

提交回复
热议问题