Table of Contents
5. Functions & Closures — How PHP Captures Context
Why this matters
Functions are where PHP does most of its thinking.
Closures are where PHP borrows context — but only when you explicitly allow it.
AI often generates code that assumes JavaScript‑style automatic capture or Python‑style scoping.
PHP is simpler, more explicit, and easier to reason about once you see the pattern.
This page gives you that pattern.
1. Functions have their own scope
A function creates a small, self‑contained world.
function add(int $a, int $b): int { return $a + $b; }
Inside the function:
- only parameters and local variables exist
nothing else is visible - nothing from the outside world is visible unless imported
no accidental access - the function ends when it returns
its world disappears immediately
This explicitness is one of PHP’s strengths.
2. Functions do not automatically see global variables
If you want a function to use a global variable, you must say so:
$counter = 0; function increment() { global $counter; $counter++; }
This is intentionally verbose
— it prevents accidental coupling and hidden dependencies.
AI often forgets this rule.
Your mental model helps you catch it.
3. Closures can capture variables — but only when told to
Closures are anonymous functions that can “use” variables from the surrounding scope.
$message = "Hello"; $fn = function() use ($message) { echo $message; };
Key idea:
- PHP does not automatically capture variables
- you must explicitly list what you want to bring in
- this keeps closures predictable and safe
This is one of the most common mistakes in AI‑generated PHP.
4. Closures can modify captured variables (with care)
If you want to modify a captured variable, you must capture it by reference:
$count = 0; $fn = function() use (&$count) { $count++; };
This is powerful, but should be used sparingly
— it can blur the boundaries of scope and make reasoning harder.
5. Arrow functions are shorthand closures
PHP’s arrow functions automatically capture variables by value:
$greeting = "Hi"; $fn = fn() => $greeting;
They are concise, but limited:
- single expression only
- no statements
- no by‑reference capture
Use them for simple transformations, not complex logic.
6. Functions and closures die at the end of the request
Just like variables:
- functions, closures, captured values
…all disappear when the request ends.
There is no persistent memory.
Summary
PHP’s function model is:
- explicit
- predictable
- easy to reason about
- free of hidden magic
Once you internalize this, you can immediately see when AI‑generated code is assuming a different language’s rules.
- Next: Classes and Autoloading
