Anonymous Functions / Closures (PHP 5.3)
TL;DR
PHP 5.3 introduced anonymous functions (closures) — function() {} expressions assignable to variables, passable as callbacks, and able to capture outer scope with use().
Explanation
PHP 5.3 (2009) added: anonymous functions: $fn = function($x) { return $x * 2; }. Scope capture with use: function() use ($var) — captures by value. use (&$var) captures by reference. Closures are instances of the Closure class. PHP 7.4 added arrow functions: fn($x) => $x * 2 — automatically capture outer scope. Closures can be bound to different objects with Closure::bind(). In PHP 8.1, closures work with first-class callable syntax: strlen(...).
Common Misconception
✗ Closures automatically capture all outer variables — they don't. You must explicitly list captured variables in use($var). Arrow functions (PHP 7.4) capture automatically.
Why It Matters
Closures enable functional programming patterns, callback-based APIs, and deferred execution — foundational to modern PHP frameworks and middleware stacks.
Common Mistakes
- Forgetting use() to capture outer variables — variable not available in closure.
- Using use(&$var) when use($var) suffices — reference capture causes subtle bugs.
- Not knowing arrow functions auto-capture — saves use() boilerplate.
Code Examples
✗ Vulnerable
$multiplier = 3;
$fn = function($x) {
return $x * $multiplier; // Error: $multiplier not defined (not captured)
};
✓ Fixed
$multiplier = 3;
// PHP 5.3+ — explicit capture:
$fn = function($x) use ($multiplier) {
return $x * $multiplier;
};
// PHP 7.4+ — auto-capture with arrow function:
$fn = fn($x) => $x * $multiplier;
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
23
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 7
Perplexity 6
Unknown AI 3
Google 2
ChatGPT 1
Ahrefs 1
Also referenced
How they use it
crawler 17
crawler_json 1
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: Low
⚡ Quick Fix
Add use($var) to capture outer variables in closures. Upgrade to PHP 7.4 arrow functions for single-expression closures that auto-capture scope.
📦 Applies To
PHP 5.3+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
function\s*\(
Auto-detectable:
✗ No
phpstan
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✓ Auto-fixable
Fix: Low
Context: Function