Function Scope, Static Variables and Recursion

5.Function Scope, Static Variables and Recursion

M

In this chapter

We'll learn which variables a function can see — only its own local variables and parameters — why a rate set at the top of the file was undefined inside the price function, the better options (a parameter or a constant) and the one to avoid (global), static variables that remember a value between calls, and recursive functions that call themselves.

14–16 min

The Problem in Real Life

To make the holiday rate easy to change, Mia puts $surchargeRate = 10; at the top of the price file and uses it in withHolidaySurcharge(): intdiv($pence * $surchargeRate, 100).

The next holiday booking comes through with no surcharge at all. The log has a warning: "Undefined variable $surchargeRate" — pointing at a line inside the function, a few lines below the line that sets it.

M

It's set right there at the top of the file. Why can't the function see it?

Mia

Inside the Function vs. Outside It

A function is a closed room

Inside a function you see only its parameters and the variables it creates — nothing from the file around it.

Getting values in

A value the function needs should come through the door — a parameter — or be a constant that's the same everywhere.

Remembering, and repeating

Static variables keep a value between calls; recursive functions call themselves for nested data.

Function Scope, Static Variables and Recursion

Scope, from the function's side: scope is the part of the code where a variable exists. Act 03 introduced it; Act 10 covers it fully, together with how PHP runs your code. This chapter looks at it from inside a function:

  • Local variables: what a function can and can't see.
  • Getting values in: parameters, constants — and global, which you should avoid.
  • Static variables: local variables that remember their value between calls.
  • Recursion: a function that calls itself.

Local variables: every call to a function gets a fresh, empty set of variables: its parameters, plus whatever it creates inside. These are local variables; they exist only during that call and vanish when it returns. And a function can't see the variables of the code around it — not even the ones at the top of the same file, which live in the global scope. That was Mia's bug: inside withHolidaySurcharge(), $surchargeRate was a brand-new, undefined local variable, so PHP warned and used null, and $pence * null is 0. The walls work both ways: a local $total inside a function can't overwrite a $total outside it. That's what makes functions safe to call from anywhere.

Mia's bug: the function can't see the file's variable
<?php
$surchargeRate = 10; // global scope
function withHolidaySurcharge(int $pence): int
{
return $pence + intdiv($pence * $surchargeRate, 100); // a new, undefined local variable
}
echo withHolidaySurcharge(2750), "\n";
// Warning: Undefined variable $surchargeRate
// 2750 — no surcharge
Local variables don't leak out, either
<?php
$total = 999;
function priceWithTowel(int $pence): int
{
$total = $pence + 250; // a local $total
return $total;
}
echo priceWithTowel(2500), "\n"; // 2750
echo $total, "\n"; // 999: the outer $total is untouched

Getting values in: there are two good ways. Pass the value as a parameter, with a sensible default: withHolidaySurcharge(int $pence, int $ratePercent = 10). Callers can see the rate and can test other rates. Or, for a value that's fixed for the whole program, use a constant (Act 03): const HOLIDAY_SURCHARGE_PERCENT = 10;. Constants are visible everywhere, including inside functions, and can't be changed by accident.

The fixes: a parameter, or a constant
<?php
declare(strict_types=1);
const HOLIDAY_SURCHARGE_PERCENT = 10;
function withHolidaySurcharge(int $pence, int $ratePercent = HOLIDAY_SURCHARGE_PERCENT): int
{
return $pence + intdiv($pence * $ratePercent, 100);
}
echo withHolidaySurcharge(2750), "\n"; // 3025: the constant
echo withHolidaySurcharge(2750, ratePercent: 20), "\n"; // 3300: another rate, for a test

global — and why not: global $surchargeRate; inside a function makes the global variable visible there, and $GLOBALS["surchargeRate"] reads it too. It works, but now the function depends on a variable that any code anywhere can change, and you can't see that dependency from the outside: withHolidaySurcharge(2750) looks self-contained but isn't. Bugs from globals are the hardest to find. Use parameters and constants instead; Act 10 shows the rare cases where globals still appear.

global works — and hides the dependency
<?php
$surchargeRate = 10;
function withHolidaySurcharge(int $pence): int
{
global $surchargeRate; // reaches out of the function
return $pence + intdiv($pence * $surchargeRate, 100);
}
echo withHolidaySurcharge(2750), "\n"; // 3025
$surchargeRate = 50; // somewhere else, someone changes it...
echo withHolidaySurcharge(2750), "\n"; // 4125 — and the "same" call gives another price

Static variables: a local variable written as static $count = 0; is created once, on the first call, and keeps its value between calls, while still being invisible outside the function. It's useful for counting calls, or for remembering a result that's expensive to work out — like loading the list of bank holidays once instead of on every price calculation. That trick is called caching. Use it sparingly: a function with a static variable remembers things, so the same call can behave differently the second time.

static: remember a value between calls
<?php
function bankHolidays(): array
{
static $holidays = null;
static $loads = 0;
if ($holidays === null) {
$loads++; // the expensive part, done once
$holidays = ["2026-12-25", "2026-12-28"];
}
echo "(loaded $loads time)\n";
return $holidays;
}
bankHolidays();
bankHolidays();
var_dump(in_array("2026-12-28", bankHolidays(), true));
// (loaded 1 time)
// (loaded 1 time)
// (loaded 1 time)
// bool(true)

Recursion: a function may call itself; that's a recursive function. It fits data that contains smaller versions of itself. BookBay sells packages: the "Groom package" is a haircut plus the "Beard package", which itself is a beard trim plus a hot towel. To price a package, price each part — and if a part is a package, price it the same way. Every recursive function needs a base case that doesn't call itself (here: a single service with a fixed price), or it calls itself forever. PHP then stops the script with an error about the call stack; in the PHP Playground the run simply stops.

Recursion: pricing packages inside packages
<?php
declare(strict_types=1);
const CATALOGUE = [
"haircut" => 2500,
"beard-trim" => 1000,
"hot-towel" => 250,
"beard-package" => ["beard-trim", "hot-towel"],
"groom-package" => ["haircut", "beard-package"],
];
function itemPrice(string $item): int
{
$entry = CATALOGUE[$item];
if (is_int($entry)) {
return $entry; // base case: a single service
}
$total = 0;
foreach ($entry as $part) {
$total += itemPrice($part); // the function calls itself
}
return $total;
}
echo itemPrice("beard-package"), "\n"; // 1250
echo itemPrice("groom-package"), "\n"; // 3750

How it all fits: the table below sums up where a function's values can come from. The short version: everything a function needs should arrive through its parameters, or be a constant.

Table — Where a function's values come from
SourceExampleVerdict
Parameterfunction f(int $ratePercent = 10)Best: visible in every call, easy to test
Constantconst HOLIDAY_SURCHARGE_PERCENT = 10;Good for values fixed for the whole program
Local variable$total = 0; inside the bodyFresh on every call
static variablestatic $calls = 0;Remembers between calls; use sparingly
global / $GLOBALSglobal $surchargeRate;Avoid: a hidden dependency

Key Takeaway

A function sees only its parameters and the variables it creates; each call starts fresh, and variables outside it — even at the top of the same file — are invisible. Pass values in as parameters (with defaults) or use constants; avoid global, which hides dependencies. static keeps a local value between calls. A recursive function calls itself for nested data and always needs a base case.

Why This Matters

The walls around a function are what make it trustworthy: it can't be broken by a variable someone renamed at the top of a file, and it can't break anything outside itself. A function whose inputs are all parameters gives the same answer for the same arguments — the property every test (Act 21) relies on.

Recursion shows up wherever data nests: packages inside packages, folders inside folders, comments with replies. Knowing the base-case rule is what keeps it from running forever.

The rate is now a constant, and withHolidaySurcharge() takes it as a default parameter. Olivia wants to try different holiday rates per day — 10% on bank holidays, 20% on Christmas Eve — so Mia stores each rule as a small function in a variable. She builds the rules, then changes the rate variable for the next one. The first rule ignores the change and keeps charging 10%. That's the next chapter: anonymous functions and closures.