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.
A function creates a small, self‑contained world.
function add(int $a, int $b): int { return $a + $b; }
Inside the function:
This explicitness is one of PHP’s strengths.
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.
Closures are anonymous functions that can “use” variables from the surrounding scope.
$message = "Hello"; $fn = function() use ($message) { echo $message; };
Key idea:
This is one of the most common mistakes in AI‑generated PHP.
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.
PHP’s arrow functions automatically capture variables by value:
$greeting = "Hi"; $fn = fn() => $greeting;
They are concise, but limited:
Use them for simple transformations, not complex logic.
Just like variables:
…all disappear when the request ends.
There is no persistent memory.
PHP’s function model is:
Once you internalize this, you can immediately see when AI‑generated code is assuming a different language’s rules.