Closures & Arrow Functions in PHP

From the PHP cheat sheet · Functions & Closures · verified Jul 2026

Closures & Arrow Functions

Anonymous functions and arrow functions

php
// Closure (anonymous function)
$greet = function($name) {
    return "Hello, $name";
};

// Closure with use
$message = 'Hello';
$say = function($name) use ($message) {
    return "$message, $name";
};

// Arrow function (PHP 7.4+)
$add = fn($a, $b) => $a + $b;

// Array operations with arrow functions
$numbers = [1, 2, 3];
$doubled = array_map(fn($n) => $n * 2, $numbers);
💡 Arrow functions auto-capture parent scope
⚡ Use & to modify external variables in closures
📌 Arrow functions always return (no void)
🔥 First-class callables simplify syntax in PHP 8.1+

More PHP tasks

Back to the full PHP cheat sheet