← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Anonymous Functions / Closures (PHP 5.3)

php PHP 5.3+ Intermediate

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;

Added 23 Mar 2026
Views 23
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
2 pings W 0 pings T 0 pings F 2 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Amazonbot 7 Perplexity 6 Unknown AI 3 Google 2 ChatGPT 1 Ahrefs 1
crawler 17 crawler_json 1 pre-tracking 2
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

✓ schema.org compliant