有没有办法将require_once()的范围显式设置为全局?

Ste*_*lla 13 php scope global-variables require-once

我正在寻找一种方法来设置范围require_once()到全局范围,何时require_once()在函数内部使用.类似下面的代码应该工作:

文件`foo.php':

<?php

$foo = 42;
Run Code Online (Sandbox Code Playgroud)

实际代码:

<?php

function includeFooFile() {
    require_once("foo.php"); // scope of "foo.php" will be the function scope
}

$foo = 23;

includeFooFile();
echo($foo."\n"); // will print 23, but I want it to print 42.
Run Code Online (Sandbox Code Playgroud)

有没有办法明确设定范围require_once()?有一个很好的解决方法吗?

Mat*_*lin 5

除了"全局化"您的变量之外,没有办法做到这一点:

global $foo;
$foo = 42;
Run Code Online (Sandbox Code Playgroud)

要么

$GLOBALS['foo'] = 42;
Run Code Online (Sandbox Code Playgroud)

打印出来时,你的值应为42.

UPDATE

关于包含类或函数,请注意除非我们讨论类方法,否则所有函数和类总是被认为是全局的.此时,类中的方法只能从类定义本身获得,而不能作为全局函数.


mpe*_*pen 1

你可以使用我写的这个 hacky 函数:

/**
 * 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当包含文件返回时,它将所有新定义的变量移回全局空间。有一个警告,如果包含的文件包含另一个文件,它将无法访问父文件中定义的任何变量,$GLOBALS因为它们尚未全球化。