🐘 PHP Intermediate

What is PHP's arrow function and how does it differ from a closure?

Why Interviewers Ask This

Mid-level PHP roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Arrow functions (PHP 7.4+), declared with fn($x) => $x * 2, are a concise syntax for closures with one key difference: they automatically capture variables from the outer scope without needing the use keyword. A regular closure requires explicit capture: function($x) use ($multiplier) { return $x * $multiplier; }. The equivalent arrow function: fn($x) => $x * $multiplier$multiplier is captured automatically. Arrow functions are limited to a single expression (the body is implicitly returned). They cannot modify outer variables (capture is by value only, not by reference). They are ideal for short callback functions in array operations: array_map(fn($n) => $n * 2, $numbers).

Pro Tip

This topic has PHP-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.