phpscopeglobal-variablesrequire-once

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


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?


Solution

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