0
0
PhpConceptBeginner · 3 min read

$GLOBALS in PHP: What It Is and How to Use It

$GLOBALS is a special PHP array that stores all global variables in your script. It allows you to access and modify global variables from anywhere, including inside functions, by using $GLOBALS['variable_name'].
⚙️

How It Works

Imagine your PHP script as a big room where you keep many boxes (variables). Normally, when you enter a smaller room inside (a function), you can't see or use the boxes in the big room directly. $GLOBALS is like a transparent window that lets you look into the big room from inside the smaller room.

In PHP, variables declared outside functions are global and not directly accessible inside functions. But $GLOBALS is a built-in associative array that holds references to all these global variables. You can use it to read or change any global variable from inside a function by referring to its name as a key.

This makes $GLOBALS a handy tool to share data across different parts of your program without passing variables explicitly.

💻

Example

This example shows how to use $GLOBALS to access and modify a global variable inside a function.

php
<?php
$counter = 10;

function increaseCounter() {
    $GLOBALS['counter'] += 5;
}

increaseCounter();
echo $counter; // Outputs the updated value
?>
Output
15
🎯

When to Use

Use $GLOBALS when you need to access or change global variables inside functions without passing them as parameters. This is useful in small scripts or quick fixes where passing variables around is inconvenient.

However, for larger or more complex programs, it's better to use function parameters or object properties to keep code clear and maintainable. Overusing $GLOBALS can make your code harder to understand and debug.

Real-world use cases include:

  • Modifying configuration settings stored in global variables.
  • Tracking counters or flags shared across multiple functions.
  • Quick prototyping where passing variables is cumbersome.

Key Points

  • $GLOBALS is a superglobal associative array holding all global variables.
  • It allows access to global variables inside functions without passing them.
  • Use it sparingly to keep code clean and easy to maintain.
  • Access variables by their name as keys, e.g., $GLOBALS['varName'].

Key Takeaways

$GLOBALS lets you access and modify global variables inside functions.
It is an associative array where keys are variable names and values are their contents.
Use $GLOBALS for quick access but prefer passing variables for clearer code.
Overusing $GLOBALS can make debugging and maintenance harder.