$GLOBALS

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 95 of 256

What Is $GLOBALS?

In simple terms: $GLOBALS is a built-in array that contains every variable defined in the global scope. Its keys are the variable names (without $), and its values are the variables' values.

Technically: $GLOBALS is a superglobal: it is available in every scope, including inside functions and methods. Reading $GLOBALS['name'] reads the global variable $name; assigning $GLOBALS['name'] = $value writes to it — from anywhere in the program.

$siteName = 'GoCourse';    // global variable
$GLOBALS['siteName'];      // 'GoCourse' — accessible in any function

Why It Exists

Regular functions cannot see global variables (see Variables Scope). $GLOBALS (and the global keyword) provide a way to reach them. In early PHP applications, this was a common way to share configuration and state. Modern code avoids global state, but you will find $GLOBALS in legacy applications, some content management systems, and debugging code — so it is important to understand how it behaves.


Reading Global Variables in a Function

<?php
$siteName = 'GoCourse';
$year = 2026;

function footerText(): string
{
    return '© ' . $GLOBALS['year'] . ' ' . $GLOBALS['siteName'];
}

echo footerText() . "\n";

Output

© 2026 GoCourse

Inside footerText(), $siteName and $year are not defined, but $GLOBALS['siteName'] and $GLOBALS['year'] read the global variables.


Writing Global Variables

<?php
$visitCount = 0;

function registerVisit(): void
{
    $GLOBALS['visitCount']++;
}

function setTheme(string $theme): void
{
    $GLOBALS['theme'] = $theme;   // creates a new global variable
}

registerVisit();
registerVisit();
setTheme('dark');

echo "Visits: $visitCount\n";
echo "Theme: $theme\n";

Output

Visits: 2
Theme: dark
  • Modifying $GLOBALS['visitCount'] changes the global $visitCount.
  • Assigning a new key creates a new global variable, here $theme.

This shows why global state is risky: after calling setTheme(), a variable appears in the global scope that was never declared there. Code that reads $theme depends on setTheme() having been called first.


$GLOBALS vs the global Keyword

<?php
$counter = 10;

function withGlobalKeyword(): void
{
    global $counter;
    $counter++;
}

function withGlobalsArray(): void
{
    $GLOBALS['counter']++;
}

withGlobalKeyword();
withGlobalsArray();

echo $counter . "\n";

Output

12
global $name;$GLOBALS['name']
SyntaxDeclared once in the function, then used as $nameArray access each time
Visible as global at the point of useNo — later lines look like local variablesYes — $GLOBALS is explicit on every line
Dynamic variable namesNoYes: $GLOBALS[$name]
Typical useLegacy codeLegacy code, debugging, framework internals

Both mechanisms share the same drawbacks; neither is recommended for new application code.


PHP 8.1 Changes: $GLOBALS Is Restricted

Before PHP 8.1, $GLOBALS behaved like a special array whose modifications — even through copies — affected global variables. PHP 8.1 restricted its use to make PHP's internals simpler and behavior more predictable.

Writing the Whole Array Is No Longer Allowed

$GLOBALS = [];                    // compile-time error in PHP 8.1+
array_pop($GLOBALS);              // error: $GLOBALS cannot be passed by reference

Writing individual elements still works: $GLOBALS['name'] = 'value';.

Copies Are Now Real Copies

<?php
$total = 10;

$copy = $GLOBALS;
$copy['total'] = 99;

echo $total . "\n";

Output (PHP 8.1 and newer)

10

Since PHP 8.1, assigning $GLOBALS to another variable creates an independent copy. Changing the copy does not affect the global $total. (In earlier versions, the change would have modified $total.)


Why Global State Should Be Avoided

<?php
$taxRate = 0.18;

function priceWithTax(float $price): float
{
    return $price * (1 + $GLOBALS['taxRate']);
}

echo priceWithTax(100) . "\n";

$GLOBALS['taxRate'] = 0.05;   // any code, anywhere, can change it

echo priceWithTax(100) . "\n";

Output

118
105

The same call returns different results because hidden global state changed between the calls. Problems with this design:

  • Hidden dependency: the signature priceWithTax(float $price) does not reveal that the function needs a tax rate.
  • Unpredictable behavior: any code can change $taxRate, and finding where it changed means searching the entire codebase.
  • Hard to test: each test must set up and reset global variables, and tests can interfere with each other.
  • Name collisions: two parts of the code (or two libraries) may use the same global name for different things.

Better Alternatives

NeedAlternative
A value a function needsPass it as a parameter
A fixed value used everywhereA constant (const TAX_RATE = 0.18;) or a class constant
Application configurationA config array loaded once and passed where needed, or a configuration object
Shared services (database connection, logger)Dependency injection: pass the service into the class or function that needs it
<?php
function priceWithTax(float $price, float $taxRate): float
{
    return $price * (1 + $taxRate);
}

echo priceWithTax(100, 0.18) . "\n";
echo priceWithTax(100, 0.05) . "\n";

Output

118
105

Now every input is visible in the call, and the function always returns the same result for the same arguments.


Legitimate Uses

$GLOBALS still has a few practical uses:

  • Debugging: inspecting which global variables exist.
  • Legacy code: maintaining older applications and plugins that rely on global variables.
  • Dynamic access: reading a global whose name is known only at runtime ($GLOBALS[$name]), for example in template engines or migration tools.

Example: Inspecting User-Defined Globals

<?php
$appName = 'GoCourse';
$version = '2.4.0';
$debug = false;

function userDefinedGlobals(): array
{
    $builtIn = ['_GET', '_POST', '_COOKIE', '_FILES', '_SERVER', '_ENV', '_REQUEST', '_SESSION', 'argv', 'argc', 'GLOBALS'];

    return array_diff_key($GLOBALS, array_flip($builtIn));
}

foreach (userDefinedGlobals() as $name => $value) {
    echo "$name = " . var_export($value, true) . "\n";
}

Output (CLI)

appName = 'GoCourse'
version = '2.4.0'
debug = false

How It Works

  • $GLOBALS also contains PHP's own superglobals and, in the command line, $argv and $argc.
  • array_diff_key() removes those built-in names, leaving only the variables defined by the script.
  • The filtering happens inside a function, so its helper variable ($builtIn) is local and does not appear in the result. The loop variables $name and $value are created only after the function has already returned its result.

Common Mistakes

Using $GLOBALS as a Configuration System

Effect: Hidden dependencies and unpredictable behavior.

Fix: Pass configuration explicitly or use a configuration object.

Writing to $GLOBALS From Many Functions

Effect: Bugs that depend on the order in which functions are called.

Fix: Return values from functions and assign them in one clear place.

Expecting Pre-8.1 Copy Behavior

Effect: Code that modifies a copy of $GLOBALS no longer changes global variables in PHP 8.1+.

Fix: Write individual elements directly: $GLOBALS['name'] = $value;.

Reading Undefined Globals

Effect: Warnings and null values.

Fix: Use $GLOBALS['name'] ?? $default, or better, avoid relying on globals.


Best Practices

  • Avoid $GLOBALS and global in new code; use parameters, return values, and constants.
  • Use dependency injection for shared services such as database connections.
  • Limit $GLOBALS to debugging, legacy maintenance, and rare dynamic-access cases.
  • In PHP 8.1+, write individual elements only; never assign or pass the whole array by reference.

Official reference: https://www.php.net/manual/en/reserved.variables.globals.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about $GLOBALS and get answers drawn from it.

Signed-in readers only.