require_once to global scope within a function require_once to global scope within a function php php

require_once to global scope within a function


To summarize all the information:

  1. functions are not an issue, they will be global anyway this way

  2. for global variables, there are 2 options:

    • declare them as global in the included file
    • declare them as global in that function (projects_init() in my case)


The above answer is right, you can use global to get what you need.In the included file just declare the variables global at the beginning of the file, this way the code will run in the function scope but it will change the global variables(yes, you have to be careful and declare everything you need to change as global but it should work), example:

function a() {     require_once("a.php");}a();echo $globalVariable;

and in the a.php file:

global $globalVariable;$globalVariable="text";


Functions are not an issue (ref):

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

About global variables: As in an existing question regarding the scope of require and the like, the scope is defined where the use is. If you need something else, there are numerous answers (my take) that show how to deal with global variables, most making use of get_defined_vars.