AlgoInsight

Q&A

What are PHP arrow functions?

By AlgoInsight Team2026-06-07php

Overview

Before PHP 7.4, anonymous functions (closures) required the verbose function () use ($var) { return ...; } syntax, explicitly listing every outer variable in a use clause. Arrow functions streamline this: they auto-capture outer variables and implicitly return their single expression, making short callbacks far cleaner.

graph TD
    A["fn(args) => expression"] --> B[Single expression only]
    A --> C[Implicit return]
    A --> D[Auto-captures outer vars BY VALUE]
    D --> E[No 'use' clause needed]
    A -.contrast.-> F["function() use(...) { return ...; }"]
    style D fill:#1e1b4b,color:#fff

Syntax

$double = fn($x) => $x * 2;
echo $double(5);   // 10

Automatic Variable Capture (the key feature)

Arrow functions capture outer-scope variables by value, automatically:

$multiplier = 3;

// Arrow function - no 'use' needed:
$times = fn($x) => $x * $multiplier;
echo $times(5);   // 15

// Equivalent classic closure - must declare 'use':
$times = function ($x) use ($multiplier) {
    return $x * $multiplier;
};

The arrow function "sees" $multiplier from the enclosing scope without listing it. Capture is by value - changing $multiplier afterward doesn't affect an already-created arrow function.

Common Use: Concise Callbacks

Arrow functions shine in array functions:

$numbers = [1, 2, 3, 4, 5];

$squared = array_map(fn($n) => $n * $n, $numbers);        // [1,4,9,16,25]
$evens   = array_filter($numbers, fn($n) => $n % 2 === 0); // [2,4]
$sum     = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0); // 15

Compare the old way: array_map(function($n) { return $n * $n; }, $numbers) - much noisier.

Limitations

// Nested capture works automatically:
$a = 1;
$f = fn($x) => fn($y) => $x + $y + $a;
echo $f(10)(100);   // 111

Arrow Function vs Closure - Summary

Feature Arrow fn Closure function
Outer variables Auto-captured by value Explicit use (...)
Body Single expression Multiple statements
Return Implicit Explicit return
Capture by reference No Yes (use (&$x))
Introduced PHP 7.4 PHP 5.3

Why This Matters in Interviews

PHP interviews use arrow functions to test modern-PHP awareness. The headline points: the fn() => single-expression syntax with implicit return, and automatic by-value capture of outer variables (vs the old use clause). Knowing the limitations - single expression, no by-reference capture - and when to fall back to a full closure demonstrates real understanding. Contrasting with JS arrow functions: PHP's don't change $this semantics the way JS arrows change this.

Common Pitfalls

References

More answers