Open In App

PHP $GLOBALS

Last Updated : 31 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

$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
<?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
<?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
<?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.

Next Article
Article Tags :

Similar Reads