Beginner LevelPHP 8+
How do PHP 7.4+ short Arrow Functions (fn() => ...) differ from standard anonymous closures?
❓ Interview Prompt: Compare short Arrow Functions (fn()) vs traditional anonymous closures (function() use ()), implicit scope capture, and single-expression limits.
PHP 7.4 introduced short Arrow Functions ('fn() => expression') as a concise syntax for anonymous closures.
Key Differences:
1
Implicit Scope Binding:
•
Traditional Closure: Requires explicitly importing outer scope variables using the 'use ($var)' syntax ('function() use ($multiplier)').
•
Arrow Function: Automatically captures outer scope variables by value implicitly without needing 'use ()'!
2
Single Expression Limit:
•
Arrow functions can contain only a single expression, which is automatically evaluated and returned.
•
Traditional closures can contain multi-line code blocks and explicit 'return' statements.
Code Implementation Example
php
<?php
$multiplier = 3;
$numbers = [1, 2, 3];
// 1. Traditional Anonymous Closure (requires explicit 'use')
$mapped1 = array_map(function ($n) use ($multiplier) {
return $n * $multiplier;
}, $numbers);
// 2. PHP 7.4+ Arrow Function (implicitly captures $multiplier by value!)
$mapped2 = array_map(fn($n) => $n * $multiplier, $numbers);
// Both return [3, 6, 9]💡Comparing traditional anonymous closures with PHP 7.4+ arrow functions.
🎯 Interview Key Takeaway
Arrow functions (fn($x) => $x * $y) automatically capture outer scope variables by value and return single expressions.
#Arrow Functions#Closures#PHP 7.4#Beginner
Back to all PHP 8+ Questions→