start learning
Image 1
500002524260112

Superglobal $GLOBAL in PHP

The $GLOBALS superglobal in PHP is used to access global variables from within a function or method. It's an associative array that contains references to all variables that are defined globally in the script. You can access these global variables by referencing them as elements of the $GLOBALS array.


Example with Clarification :

Let's create an example to illustrate how to use the $GLOBALS superglobal to access and modify global variables within a function :

$globalVar = 42; // A global variable

function modifyGlobalVar() {
    $GLOBALS['globalVar'] += 10; // Access and modify the global variable
}

modifyGlobalVar(); // Call the function
echo $globalVar; // Output: 52 (the global variable has been modified)
  1. We define a global variable named $globalVar with an initial value of 42.
  2. We create a function called modifyGlobalVar. Inside the function, we access the global variable $globalVar using the $GLOBALS superglobal and then modify it by adding 10.
  3. We call the modifyGlobalVar function, which modifies the global variable using the $GLOBALS array.
  4. After calling the function, we echo the value of $globalVar to the screen, and it now reflects the modified value of 52.

In this example, the $GLOBALS superglobal allows us to access and modify a global variable from within the function's scope. It's important to note that using global variables and the $GLOBALS superglobal should be done judiciously, as excessive use of global variables can make code harder to understand and maintain.