AnyCompiler

Closures and Arrow Functions

An anonymous function is written function ($params) { ... } with no name after function — it's a value, assignable to a variable, like any other. By default it can't see variables from the scope it was written in; use ($var) on the function header explicitly captures $var by value from the surrounding scope, letting the closure read it.

fn($params) => $expression, added in PHP 7.4, is a shorter arrow-function form for the common case of a closure that's just one expression — and unlike the function (...) use (...) form, it captures outer variables automatically, with no use list needed. It's PHP's answer to Python's lambda or JavaScript's arrow functions, and it's what you'll see passed into array_map(), array_filter(), and friends in idiomatic modern PHP.

<?php
$multiplier = 3;
$multiply = function ($x) use ($multiplier) {
    return $x * $multiplier;
};
echo $multiply(5), "\n";

$square = fn($x) => $x * $x;
echo $square(6), "\n";

$nums = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $nums);
print_r($doubled);
Output
15
36
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

$multiply(5) is 5 * 3 using the $multiplier captured explicitly with use; $square(6) is 6 * 6 using the shorter fn() form with no use list at all. array_map(fn($n) => $n * 2, $nums) applied that arrow function to every element of $nums in one call — the kind of transformation idiomatic PHP almost always reaches for array_map over a hand-written loop. Next: classes and objects — the class keyword, $this, constructors, and properties.

Practice exercise

Given $nums = [1, 2, 3, 4], use array_map() with an arrow function to square every element, then echo the results joined with ", " using implode().