Anonymous Functions and Closures
Functions without a name, capturing outer variables, and the compact arrow function syntax.
2 min read
PHP treats functions as values you can store in a variable, pass as an argument, or return from another function — starting with anonymous functions.
Anonymous functions
<?php
$greet = function ($name) {
return "Hello, $name!";
};
echo $greet("Amara");An anonymous function (also called a closure) has no name of its own — it's assigned directly to a variable, which is then called just like a named function. This is the shape most callbacks take when passed to functions like array_map() or usort().
Capturing outer variables with use
<?php
$taxRate = 0.08;
$addTax = function ($price) use ($taxRate) {
return $price * (1 + $taxRate);
};
echo $addTax(100); // 108By default, an anonymous function can't see variables from the surrounding scope — use ($taxRate) explicitly imports it. Without use, referencing $taxRate inside the closure would trigger an "undefined variable" warning, even though it clearly exists just outside.
Capturing by reference
<?php
$total = 0;
$addToTotal = function ($amount) use (&$total) {
$total += $amount;
};
$addToTotal(10);
$addToTotal(25);
echo $total; // 35use (&$total) captures $total by reference instead of by value — changes made inside the closure persist in the outer variable after the closure returns. Without the &, each call would modify its own private copy, and the outer $total would still be 0.
Arrow functions: a shorter syntax
<?php
$taxRate = 0.08;
$addTax = fn($price) => $price * (1 + $taxRate);
echo $addTax(100); // 108Arrow functions (fn(...) => expression) automatically capture any outer variable they reference — no use needed — but are limited to a single expression, whose result is returned implicitly. They're a good fit for the short, one-line callbacks passed to array_map(), array_filter(), and similar functions; reach for a full anonymous function when the logic needs more than one statement.
Passing a closure as a callback
<?php
$numbers = [5, 3, 8, 1];
usort($numbers, fn($a, $b) => $a <=> $b);
print_r($numbers); // [1, 3, 5, 8]usort() sorts an array using a custom comparison function — here, the spaceship operator <=> returns -1, 0, or 1 depending on whether $a is less than, equal to, or greater than $b, which is exactly what a comparison callback is expected to return. This pattern — a built-in function taking a closure to customize its behavior — is everywhere in PHP's standard library.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.