Variable Scope, static & References

Variable Scope, static & References in PHP: --- In an engineering firm's drawing office, each draughtsman works at a private drawing board.


The Analogy: The Drawing Office

In an engineering firm's drawing office, each draughtsman works at a private drawing board. The board holds whatever drawing that person is developing, and it is theirs alone: the draughtsman two desks over cannot see it, reach across to it, or accidentally smudge it. When you sit down at your board and pin up a fresh sheet, you start from a clean surface with none of your neighbour's lines on it. This private board is a function's local scope. Every variable you create inside a function lives on that function's own board, invisible to the rest of the program, and it is wiped clean when the function ends and the next call pins up a new sheet.

At the centre of the office stands the master archive -- the great plan-chest of drawings the whole firm shares. Anyone may draw a sheet from it, but precisely because everyone can, changes to an archived master ripple out to every project that relies on it, and it is not always clear who altered what. That shared archive is global scope, reached from inside a function only by explicitly declaring global on a variable or reaching into the $GLOBALS array. Convenient, occasionally necessary, and quietly dangerous: a function that reaches into the archive is coupled to the whole building.

Two features complicate the tidy picture of a board wiped clean each time. First, each draughtsman has one lockable drawer in their board that is not cleared at the end of the day -- a running calculation or a tally sheet kept there persists to the next shift, while remaining private to that board. That drawer is a static local variable: local in visibility, but surviving across calls rather than resetting. Second, when a colleague asks to work on one of your drawings, you face a choice. You can run off a dyeline copy and hand them that, so their red-pen corrections stay on the copy and your original is untouched -- passing by value. Or you can unpin the original linen tracing and hand them that very sheet, so whatever they mark is now on the one and only master -- passing by reference, written in PHP with an & before the parameter.

The failures follow the choice of what you hand over. Passing by value is safe but forgetful: the colleague's improvements live only on their copy and never reach your board unless they hand something back. Passing by reference is powerful but perilous, and its worst failure is silent. You hand over the original expecting one small note, the colleague reorganises the whole sheet, and your master is changed without your ever seeing it happen -- action at a distance, with no copy to fall back on. Worse still is forgetting to take the original back off their desk: leave a live reference lying around and a later, unrelated piece of work can write straight through it onto your master, corrupting a drawing nobody meant to touch. That lingering-reference accident is one of the most notorious bugs in PHP, and the real-world example below reproduces it exactly.


Syntax or Core Structure

Variables created inside a function are local to it: they are not visible outside, and each call starts fresh. A static local variable is the exception -- it is initialised once and retains its value between calls to that function. A function cannot see a variable from the enclosing scope unless it is passed in, declared global, or captured by a closure.

<?php

function nextTicket(): int
{
    static $n = 0;   // initialised once, survives across calls
    $n++;
    return $n;
}

echo nextTicket(), "\n";   // 1
echo nextTicket(), "\n";   // 2
echo nextTicket(), "\n";   // 3

$outside = 'hello';

function peek(): string
{
    // $outside is NOT visible here -- a fresh, empty local scope
    return $outside ?? 'not in scope';
}

echo peek(), "\n";

The static $n keeps counting because it is initialised only on the first call and persists afterwards, so three calls yield 1, 2, 3. Inside peek, the outer $outside simply does not exist -- the null-coalescing operator quietly supplies the fallback rather than raising a warning -- proving that function scope is isolated by default.

Output:

1
2
3
not in scope

If peek genuinely needed the outer value, the right move is to pass it as an argument; reaching for global $outside; would work but couples the function to a specific outer variable and is best avoided.


Technical Depth: Scope Kinds and the Two Ways to Pass

The kinds of scope

PHP's scoping is deliberately simple compared with many languages: there is no block scope, so a variable set inside an if or for is visible for the rest of the function. What matters is the function boundary. The table lays out where each kind of variable lives and how long it lasts.

KindVisible whereLifetime
LocalInside its function onlyCleared when the function returns
Static localInside its function onlyPersists across calls
GlobalAt top level; inside only via globalThe whole request
SuperglobalEverywhere, no declarationThe whole request

Superglobals such as $_GET, $_POST, $_SERVER, and $GLOBALS are the exception to the isolation rule: they are visible inside every function without any declaration. That convenience is also why reading request data directly from $_GET deep inside your code is discouraged -- it hides a function's real dependencies, exactly as an unannounced trip to the master archive does.

Passing by value versus by reference

By default PHP passes arguments by value: the function receives a copy, and changes to the parameter do not touch the caller's variable. Prefixing the parameter with & passes by reference instead, aliasing the caller's variable so the function can change it in place.

<?php

function bumpValue(int $n): void
{
    $n++;   // changes only the local copy
}

function bumpRef(int &$n): void
{
    $n++;   // changes the caller's variable
}

$a = 10;
bumpValue($a);
echo $a, "\n";   // still 10

$b = 10;
bumpRef($b);
echo $b, "\n";   // now 11

bumpValue increments a copy, so $a is unchanged at 10. bumpRef takes $b by reference, so its increment is written straight back to the caller's variable, which becomes 11. The single & is the whole difference, and it is easy to miss when reading a signature -- which is exactly why by-reference parameters must be used sparingly and named clearly.

Output:

10
11

Most PHP code should pass by value and return new values; reserve by-reference parameters for the rare cases where mutating the caller's variable is genuinely the clearest design, such as an in-place sort.

Objects are passed by handle, not by reference

Here is where scope and references trip up almost everyone. When you pass an object to a function, PHP does not copy the object and it does not pass it by reference either. It passes a copy of the handle -- a lightweight identifier that points at the one shared object. Reassigning the parameter swaps only the local handle, so the caller sees nothing; but reaching through the handle to change a property mutates the single shared object, and the caller sees that immediately.

<?php
class Box {
    public int $n = 1;
}

function replace(Box $b): void {
    $b = new Box();   // swaps only the local handle
    $b->n = 99;       // touches the new local object, not the caller's
}

function fill(Box $b): void {
    $b->n = 5;        // reaches through the shared handle
}

$crate = new Box();
replace($crate);
echo $crate->n, "\n";  // still 1 -- replace() could not reach it

fill($crate);
echo $crate->n, "\n";  // now 5 -- fill() mutated the shared object

Output:

1
5

This is why you almost never need & on an object parameter: the handle already gives every function a route to the same object. Add & to an object parameter only when you truly need to reassign the caller's variable to a different object from inside the function, which is rare and usually a sign the design should return the new object instead.


Real World Example: Normalising Category Tags

A blog stores each post's category tags and wants them normalised to lower case before display. The script below lowercases the tags in place with a by-reference foreach, counts how many it changed, and then renders the list in a second loop. It looks entirely reasonable, and it harbours one of the most infamous bugs in PHP.

<?php
declare(strict_types=1);

$tags = ['php', 'Web', 'API'];

$changed = 0;
foreach ($tags as &$tag) {      // by reference, to edit in place
    $lower = strtolower($tag);
    if ($lower !== $tag) {
        $changed++;
    }
    $tag = $lower;
}
// BUG: no unset($tag) here -- $tag still references the last element

echo "CATEGORY TAGS\n";
echo str_repeat('-', 13), "\n";
foreach ($tags as $i => $tag) {  // reuses $tag, which is still a live reference
    echo "[{$i}] {$tag}\n";
}
echo "normalised {$changed} of ", count($tags), " tags\n";

Output:

CATEGORY TAGS
-------------
[0] php
[1] web
[2] web
normalised 2 of 3 tags

The normalisation itself is correct: 'php' was already lower case, 'Web' and 'API' were changed, so the count of 2 of 3 is right. The first loop leaves $tags as ['php', 'web', 'api'], exactly as intended. Everything about the transformation is sound.

But look at index 2: it reads web, when it should read api. This is the classic dangling-reference bug, and it is a genuine defect in the code shown, not a rough edge. Because the first foreach used &$tag, the variable $tag remains a live reference to $tags[2] after the loop ends -- the linen tracing left on the colleague's desk. The second foreach then reuses that same $tag name as its loop variable, so every assignment it makes writes through the reference into $tags[2]. On the final iteration $tags[2] has already been overwritten with the value of $tags[1] (web), and the original api is gone. The fix is a single line: unset($tag); immediately after the by-reference loop, which breaks the alias. Better still, avoid the reference entirely -- $tags = array_map('strtolower', $tags); normalises the array with no reference to leak, which is why building a new value is almost always safer than mutating in place.


Common Mistakes

  1. Forgetting unset after a by-reference foreach. The loop variable remains a live reference to the last element, and any later reuse of that name writes through it, corrupting the array. Call unset($item); immediately after the loop, or avoid the reference altogether.
  1. Expecting a function to see outer variables. PHP functions do not inherit the enclosing scope; a variable from outside is simply undefined inside unless passed in, declared global, or captured by a closure. Pass what the function needs as arguments.
  1. Reaching for global out of convenience. Declaring global $config; couples the function to a specific outer variable and hides its real inputs. Pass the value in as a parameter so the dependency is visible in the signature.
  1. Re-initialising a static on every call. Writing static $n = 0; $n = 0; defeats the point -- the second line resets it each time. The initialiser runs once; do not overwrite the value unconditionally in the body.
  1. Assuming an inner block has its own scope. PHP has no block scope, so a variable set inside an if or for is visible for the rest of the function. Do not expect a loop or conditional to contain its variables.
  1. Missing the & when you meant to mutate. Passing by value and then wondering why the caller's variable did not change is a common trip-up. Only a parameter declared &$x writes back; check the signature before assuming mutation.
  1. Adding & when a return value would be clearer. By-reference parameters make call sites lie about what they change. Prefer returning a new value and reassigning at the call site, so the mutation is visible where it happens.
  1. Sharing a static where per-instance state is needed. A static local is shared across every call to that function, including from different objects. When state should belong to an object, use a property, not a function-level static.
  1. Reading superglobals deep inside logic. Pulling $_GET['page'] straight out of a low-level function hides its dependency on request data and makes it impossible to test in isolation. Read request input once at the edge and pass it inward.

Best Practices

  • Keep variables local and pass everything a function needs through its parameters, so each function's inputs are visible in its signature.
  • Default to passing by value and returning new values; reserve & for the rare case where mutating the caller's variable is genuinely the clearest design.
  • When you do use a by-reference foreach, call unset on the loop variable the moment the loop ends, and prefer array_map or a rebuilt array where you can.
  • Use a static local only for state that is genuinely per-function and must persist, such as a memoisation cache or a call counter, and document why.
  • Avoid global; if several functions need shared state, pass an object or use dependency injection rather than reaching into global scope.
  • Read superglobals once at the boundary of your application and pass the extracted, validated values inward, keeping inner functions testable.
  • Name by-reference parameters and the functions that use them clearly, so a reader is not surprised that the caller's variable changed.
  • Remember that PHP has no block scope: declare and initialise a variable before the block that uses it when clarity demands, rather than relying on where it happens to be set.

Practice Exercises

  1. Write a counter() function using a static local that returns 1, 2, 3 on successive calls, then add a second function with its own static and confirm the two counters are independent. Explain why the state does not leak between them.
  1. Write addTax(float &$price, float $rate): void that raises the caller's price by the given rate in place, and a by-value equivalent withTax(float $price, float $rate): float. Call each and show which one changes the original variable, explaining the role of the &.
  1. Reproduce the dangling-reference bug: normalise an array with a by-reference foreach, then loop over it again reusing the same variable name, and observe the corrupted last element. Fix it two ways -- with unset and with array_map -- and confirm both give the correct result.
  1. Write a function that needs a configuration value and implement it twice: once by declaring global $config; and once by accepting $config as a parameter. Explain which version is easier to test and why depending on global scope is the weaker design.