Skip to content

PHP Tutorial Superglobals

$GLOBALS

Lesson 154 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

$GLOBALS is an array of every variable in the global scope. Because it is a superglobal, you can use it inside functions without global.

index.php
PHP
<?php
$siteName = "Code Corner";

function showSite(): void
{
    echo $GLOBALS["siteName"];
}

showSite();
Output
OUTPUT
Code Corner

Writing a global variable

You can create or change a single global through its key.

index.php
PHP
<?php
$counter = 0;

function increase(): void
{
    $GLOBALS["counter"]++;
}

increase();
increase();

echo $counter;
Output
OUTPUT
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 aliasYesNo
Shows where the data comes fromA littleClearly

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:

index.php
PHP
<?php
function showSite(string $siteName): void
{
    echo $siteName;
}

showSite("Code Corner");
Output
OUTPUT
Code Corner
info
WordPress uses globals heavily
Core WordPress still relies on globals such as $post and $wpdb. You will use global $post; in themes. In your own code, prefer parameters or a small class.