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

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

提交回复
热议问题