PHP $GLOBALS
$GLOBALS is a built-in PHP superglobal associative array that stores all global variables in a PHP script. It provides a way to access global variables from any scope, including inside functions, classes, or methods, without needing to pass them as arguments or use the global keyword.
To access a global variable within a function, you must either declare it as global using the global keyword or reference it through the $GLOBALS array.
How Does $GLOBALS Work?
Here is a simple example to illustrate why $GLOBALS is needed:
<?php
$message = "Hello, World!";
function printMessage() {
echo $message; // Undefined variable error
}
printMessage();
?>
Notice: Undefined variable: message
Inside printMessage(), $message is undefined because the function has its own local scope.
Now, using $GLOBALS:
<?php
$message = "Hello, World!";
function printMessage() {
echo $GLOBALS['message']; // Access global variable directly
}
printMessage();
?>
Output
Hello, World!
The function accesses the global variable $message through $GLOBALS['message'].
Accessing and Modifying Global Variables Using $GLOBALS
You can not only read but also change global variables inside functions via $GLOBALS.
<?php
$count = 5;
function incrementCount() {
$GLOBALS['count']++;
}
incrementCount();
incrementCount();
echo $count; // Output: 7
?>
Output
7
Here, the function increments the global $count by modifying it inside $GLOBALS.
When to Use $GLOBALS
- When you need to access or modify global variables inside functions without declaring each one as global.
- When dealing with many global variables and you want a consistent, readable approach.
- Useful in procedural code or legacy scripts where passing parameters is impractical.
Best Practices for Using $GLOBALS
- Limit usage to cases where other alternatives (function parameters, class properties) are impractical.
- Avoid global state whenever possible; encapsulate variables within functions or classes.
- Use $GLOBALS primarily for small scripts or debugging.
- Document variables accessed via $GLOBALS are clearly for maintainability.