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
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.