This article demonstrates how to declare a global variable in PHP.

1. Using $GLOBALS variable

The recommended solution to declare a global variable is to use the $GLOBALS super variable, which is an associative array of all variables defined in the global scope. You can add your variables to the $GLOBALS super variable and use it like follows:

Download  Run Code

 
Note that if a variable is declared outside a function, it has a global scope. In other words, you can access a global variable within a function using the global keyword or access it using the $GLOBALS super global array.

Download  Run Code

2. Using class

Alternatively, you can create a Globals class containing references to all variables. A typical implementation of the Globals class would look like below:

Download  Run Code

3. Using define() function

Finally, you can use the define() function to define named constants that are accessible throughout the script. The advantage of using this method over all the others is that the constant value cannot be modified once it has been created. The following example provides an illustration.

Download  Run Code

That’s all there is to declaring a global variable in PHP.