问题描述
我正在寻找一种将 require_once()
范围设置为全局范围的方法,当 require_once()
在函数内部使用。像下面的代码应该工作:
文件`foo.php':
<?php
$ foo = 42;
实际代码:
<?php
函数includeFooFile(){
require_once(foo.php); //foo.php的作用域是函数作用域
}
$ foo = 23;
includeFooFile();
echo($ foo。\\\
); //将打印23,但我希望它打印42.
有没有办法显式设置 require_once()
的范围?是否有一个很好的解决方法?
您可以使用这个哈希函数我写道:
/ **
*提取所有全局变量作为引用并包含文件。
*用于包含旧版插件。
*
* @param string $ __ filename__要包含
的文件* @param array $ __ vars__要提取到本地作用域的额外变量
* @throws异常
* @return void
* /
函数GlobalInclude($ __ filename__,& $ __ vars__ = null){
if(!is_file($ __ filename__))抛出新的异常('File'。$ __ filename__。'不存在');
提取($ GLOBALS,EXTR_REFS | EXTR_SKIP);
if($ __ vars__!== null)extract($ __ vars__,EXTR_REFS);
unset($ __ vars__);
包含$ __ filename__;
unset($ __ filename__);
foreach(array_diff_key(get_defined_vars(),$ GLOBALS)为$ key => $ val){
$ GLOBALS [$ key] = $ val;
$ / code>
它会将新定义的变量移回全局空间包含文件返回。有一点需要注意的是,如果包含的文件包含另一个文件,它将无法通过 $ GLOBALS
访问父文件中定义的任何变量,因为它们尚未全球化还有。
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 following code should work:
file `foo.php':
<?php
$foo = 42;
actual code:
<?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.
Is there a way to explicitly set the scope of require_once()
? Is there a nice workaround?
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.
这篇关于有没有办法将require_once()的作用域明确地设置为全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!