Scope Rules and $GLOBALS

1.Scope Rules and $GLOBALS

M

In this chapter

We'll learn the complete rules of variable scope in PHP: the global scope shared by the main file and every file it includes, why loops and if blocks don't create a scope, what the global keyword and $GLOBALS really do, why functions and constants are visible everywhere but variables aren't, and the superglobals that PHP fills in for every request.

14–16 min

The Problem in Real Life

Thursday, 20 days before launch. booking.php has grown to 900 lines in one file, and Marcus wants it split into smaller files before launch. First, though, a bug. A customer picks Tuesday on the booking page, and the slot list below says "Closed" — Sunday's answer.

At the top of the page, Mia recently added a week overview: foreach ($week as $date) { ... }. Further down, the slot list comes from a helper she wrote weeks ago: function daySlots() { global $date; ... }. The $date that the helper reads is the customer's Tuesday — or it was, until the week overview ran.

M

The loop finished long before the slot list. Why does it still change my $date?

Mia

Global Variables vs. Values Passed In

Loops don't have walls

Only functions create a new scope. A foreach variable at the top of a file is an ordinary global variable — and it outlives the loop.

global is a shared line

global $date doesn't copy the value. It connects the function to whatever $date holds at the moment of the call.

Some names are everywhere

Functions, constants and superglobals like $_GET are visible in every function. Ordinary variables never are.

Scope Rules and $GLOBALS

Scope, the full picture: Act 03 introduced scope and Act 09 looked at it from inside a function. This chapter puts all the rules in one place, before the code is split into files:

  • The two scopes: the global scope and function scope — and what does not create a scope.
  • global and $GLOBALS: the two ways into the global scope, and why they're risky.
  • Which names are visible where: variables vs. functions, constants and classes.
  • Superglobals: the variables PHP fills in and makes visible everywhere.

Two scopes, and only functions make a new one: PHP has exactly two kinds of variable scope. The global scope is the top level of the file that PHP runs — and, as the next chapter shows, of every file it includes. Each function call gets its own local scope. Nothing else creates a scope: not if, not foreach, not while, not a pair of curly braces. A variable created inside a loop at the top of a file is a global variable like any other, and after the loop it still holds the last value. That's the first half of Mia's bug: after foreach ($week as $date), the global $date was "Sunday", the last day of the week, and the customer's Tuesday was gone.

Loops and if blocks don't create a scope
<?php
$week = ["Monday", "Tuesday", "Sunday"];
foreach ($week as $day) {
$lastSeen = $day;
}
if (true) {
$insideIf = "still here";
}
echo $day, "\n"; // Sunday: the loop variable outlives the loop
echo $lastSeen, "\n"; // Sunday
echo $insideIf, "\n"; // still here

The global keyword: global $date; inside a function doesn't copy anything. It makes the local name $date a reference (Act 03) to the global variable $date, so the function sees — and can change — whatever that variable holds at the moment of the call. That's the second half of the bug: daySlots() read the global $date after the loop had changed it. Every line of every file in the request shares the global scope, so a function that uses global depends on all of them. The fix is the one from Act 09: pass the date in as a parameter, daySlots(string $date), and keep the customer's choice in a variable the loop doesn't reuse.

Mia's bug: global reads the value at the moment of the call
<?php
function daySlots(): string
{
global $date; // linked to the global $date
return $date === "Sunday" ? "Closed" : "9:00 9:30 10:00";
}
$date = "Tuesday"; // the customer's choice
foreach (["Monday", "Tuesday", "Sunday"] as $date) { // the week overview reuses $date
// ... prints the week ...
}
echo "Slots for Tuesday: ", daySlots(), "\n"; // Slots for Tuesday: Closed
The fix: pass the value in
<?php
declare(strict_types=1);
function daySlots(string $date): string
{
return $date === "Sunday" ? "Closed" : "9:00 9:30 10:00";
}
$chosenDate = "Tuesday";
foreach (["Monday", "Tuesday", "Sunday"] as $weekDay) {
// ... prints the week ...
}
echo "Slots for $chosenDate: ", daySlots($chosenDate), "\n"; // Slots for Tuesday: 9:00 9:30 10:00

$GLOBALS: $GLOBALS is an array of every global variable, keyed by name, and it's visible everywhere. $GLOBALS["date"] reads the global $date from inside any function, and $GLOBALS["date"] = "2026-11-10"; changes it. Since PHP 8.1 you can read and change single entries, but you can't replace or copy the whole array as if it were a normal variable. It has exactly the same problems as global: a hidden dependency that any code can break. You'll see it in old code; don't write it.

$GLOBALS reaches every global variable
<?php
$date = "Tuesday";
function readDate(): string
{
return $GLOBALS["date"]; // read a global from inside a function
}
function changeDate(): void
{
$GLOBALS["date"] = "Sunday"; // ...or change it, from anywhere
}
echo readDate(), "\n"; // Tuesday
changeDate();
echo $date, "\n"; // Sunday: changed by a function that took no parameters

Which names are visible where: the walls of a function only stop variables. Functions, constants and classes have global names: once declared, formatPrice(), HOLIDAY_SURCHARGE_PERCENT or a class (Act 11) can be used in every function and every file, without passing anything in. That's why formatPrice() works inside another function, but $rate doesn't. (Act 13's namespaces add a "first name" to these global names so two libraries can't clash.) You'll also meet ::, whose official name is the scope resolution operator: it reaches into a class, like Booking::MAX_PER_DAY, and belongs to Act 11.

Functions and constants are visible everywhere; variables aren't
<?php
const SHOP_NAME = "Tom's Barbershop";
$rate = 10;
function formatPrice(int $pence): string
{
return "£" . number_format($pence / 100, 2);
}
function receiptLine(int $pence): string
{
$seesRate = isset($rate) ? "yes" : "no";
return SHOP_NAME . ": " . formatPrice($pence) . " (sees \$rate: $seesRate)";
}
echo receiptLine(2750), "\n"; // Tom's Barbershop: £27.50 (sees $rate: no)

How long variables live: a local variable lives until its function call returns; a static variable (Act 09) and a global variable live until the end of the request, and not a moment longer. Chapter 3 explains why that matters: no variable survives from one visitor's request to the next.

Superglobals: a few variables are visible everywhere — in the global scope and in every function, with no global needed. PHP fills them in at the start of each request: $_GET (values from the URL), $_POST (submitted forms), $_COOKIE, $_FILES (uploads), $_SERVER (details about the request and the server), $_ENV (environment variables), $_REQUEST (GET, POST and cookies mixed together — avoid it), $_SESSION (Act 17) and $GLOBALS. They hold input from outside, so treat their contents as untrusted (Act 20). A good habit: read them once, at the top of the page, check the values, and pass them into your functions as parameters. A helper that reads $_GET itself can't be reused in a terminal script, where $_GET is empty — chapter 3 again. Act 16 covers them all in detail. The table below sums up the scope rules.

Table — Who can see what
NameVisible in the global scope?Visible inside functions?Lives until
A variable at the top levelYesNo (only with global or $GLOBALS)The end of the request
A variable inside a functionNoOnly in that callThe call returns
A static variableNoOnly in that functionThe end of the request
A loop variable at the top levelYes, even after the loopNoThe end of the request
A function, constant or classYesYesThe end of the request
A superglobal ($_GET, $_SERVER …)YesYesThe end of the request
Superglobals: visible everywhere, filled in by PHP
<?php
function requestedDate(): string
{
return $_GET["date"] ?? "no date in the URL"; // no global needed
}
function howWasThisRun(): string
{
return $_SERVER["REQUEST_METHOD"] ?? "not a web request";
}
echo requestedDate(), "\n"; // no date in the URL: the Playground has no URL
echo howWasThisRun(), "\n"; // not a web request

Key Takeaway

PHP has two variable scopes: the global scope (the top level of the main file and every included file) and one local scope per function call. Loops, ifs and braces don't create a scope, so a loop variable at the top level is a global that outlives the loop. global and $GLOBALS connect a function to shared global variables — a hidden dependency; pass values in as parameters instead. Functions, constants, classes and superglobals are visible everywhere; ordinary variables never are.

Why This Matters

Splitting a project into files only works if you know which code can see which variables. Every global variable is shared by every line of every file in the request — so the more code there is, the more ways there are for one part to break another without touching it.

The habit that prevents all of this is simple and you already know it: values go into functions as parameters and come out with return; superglobals are read once at the top and passed on. Everything in the next chapters, and every framework you'll use, is built on that habit.

daySlots() now takes the date as a parameter, and the customer's Tuesday stays Tuesday. Time to split the 900 lines. Mia moves the time helpers, the slot functions and the prices into their own files, and writes a small script for the terminal that sends tomorrow's reminders. Within an hour, three things break: the booking page always shows 5 November, the reminder script dies with "Cannot redeclare function formatTime()" — although the website works — and the server can't find config.php. That's the next chapter: include, require and file paths.