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

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

提交回复
热议问题