SyntaxStudy
Sign Up
PHP Anonymous Functions & Closures
PHP Beginner 1 min read

Anonymous Functions & Closures

Anonymous Functions & Closures

Anonymous functions are functions without a name. They can be stored in variables or passed as arguments.

Closures

Use use($var) to bring outer variables into the function's scope.

Arrow Functions (PHP 7.4+)

Short syntax: fn($x) => $x * 2. Automatically captures outer scope (no use needed).

Example
<?php
// Anonymous function
$greet = function(string $name): string {
    return "Hello, $name!";
};
echo $greet("Bob"); // Hello, Bob!

// Closure with use
$prefix = "Mr.";
$formal = function(string $name) use ($prefix): string {
    return "$prefix $name";
};
echo $formal("Smith"); // Mr. Smith

// Arrow function (PHP 7.4+)
$double = fn($n) => $n * 2;
$nums = [1, 2, 3, 4];
$doubled = array_map(fn($n) => $n * 2, $nums);
?>