$GLOBALS is an array of every variable in the global scope. Because it is a superglobal, you can use it inside functions without global.
<?php
$siteName = "Code Corner";
function showSite(): void
{
echo $GLOBALS["siteName"];
}
showSite();
Code Corner
Writing a global variable
You can create or change a single global through its key.
<?php
$counter = 0;
function increase(): void
{
$GLOBALS["counter"]++;
}
increase();
increase();
echo $counter;
2
PHP 8.1 restrictions
In PHP 8.1, $GLOBALS became a read-only copy of the global symbol table, with one exception: writing to a single key ($GLOBALS["x"] = 1) is still allowed. These no longer work:
$GLOBALS = [];foreach ($GLOBALS as &$value)(by reference)array_pop($GLOBALS)and other functions that take the whole array by reference
If you maintain old code that does that, it needs a change.
$GLOBALS vs the global keyword
global $x; | $GLOBALS["x"] | |
|---|---|---|
| Creates a local alias | Yes | No |
| Shows where the data comes from | A little | Clearly |
Both do the same job. Neither is a good habit.
The problem with globals
- A function hides its inputs. You cannot tell what it needs by reading its signature.
- Any code anywhere can change the value.
- Testing is harder.
Pass what the function needs as parameters instead:
<?php
function showSite(string $siteName): void
{
echo $siteName;
}
showSite("Code Corner");
Code Corner
WordPress uses globals heavily
$post and $wpdb. You will use global $post; in themes. In your own code, prefer parameters or a small class.