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

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

    I haven't tried it (since using global vars is a bad idea tbh) but this could potentially work:

    require_once '...';
    $GLOBALS = array_merge($GLOBALS, get_defined_vars());
    

    Alternatively you can just do it manually:

    foreach (get_defined_vars() as $k => $v) {
        $GLOBALS[$k] = $v;
    }
    
    0 讨论(0)
  • 2021-02-19 12:26

    Apart from "globalizing" your variable, there is no way to do this:

    global $foo;
    $foo = 42;
    

    OR

    $GLOBALS['foo'] = 42;
    

    Then your value should be 42 when you print it out.

    UPDATE

    Regarding the inclusion of classes or functions, note that all functions and classes are always considered global unless we are talking about a class method. At that point, the method in a class is only available from the class definition itself and not as a global function.

    0 讨论(0)
  • 2021-02-19 12:28

    As the scope is explicitly defined where you use require and the like, you would need to specify what to do with the variables inside the scope of the function:

    function includeFooFile() {
        require_once("foo.php"); // scope of "foo.php" will be the function scope
    
        foreach (get_defined_vars() as $k => $v)
        {
            $GLOBALS[$k] = &$v;
        }
    }
    

    This example takes care of both, variables and references which might be what you're looking for. Demo. Please note that require_once would only work once and would only define the variables once.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-19 12:39

    Pending on your exact requirements, you could use constants. Require your file in the global scope, but inside it set a constant.

    IE file.php:

    define('MY_CONSTANT', 42);
    

    Then anywhere in your script just use MY_CONSTANT to refer to the value, you won't be able to edit once it's been set though. Other than that, you could globalize your variable as the other answer says, but it's not 100% clear what you're trying to achieve other than simply retrieving a value from the included file? In which case constants should be fine.

    Update: Now you've explained that you want an objects properties to be available everywhere, I suggest you look into creating a static class, which once instantiated in your global scope can be used anywhere in your app. Read the linked manual page, it has a bare-bones example.

    0 讨论(0)
  • 2021-02-19 12:43

    This is definitely not a "nice" work around but it would work:

    function includeFooFile() {
      require_once("foo.php");
      foreach (get_defined_vars() as $key => $value) {
        // Ignore superglobals
        if (!in_array($key, array('GLOBALS','_SERVER','_GET','_POST','_FILES','_COOKIE','_SESSION','_REQUEST','_ENV'))) {
          $GLOBALS[$key] = $value;
        }
      }
    }
    

    However, your included file cannot define any functions or classes (and possibly some other things as well that I cannot currently think of) because it will result in a parse error, since you cannot nest classes or functions.

    EDIT apparently you can include functions in your file. I had always thought you couldn't but after testing it seems that you can.

    0 讨论(0)
提交回复
热议问题