PHP Closures and Anonymous Functions Explained

Closures let you define a function inline and capture variables from the surrounding scope — essential for callbacks, and the foundation of how array functions like array_map take custom logic.

$taxRate = 0.19;

// use() captures $taxRate from the enclosing scope
$addTax = function (float $price) use ($taxRate) {
    return $price * (1 + $taxRate);
};

echo $addTax(100); // 119.0

// Arrow functions (PHP 7.4+) auto-capture the enclosing scope
$addTaxShort = fn($price) => $price * (1 + $taxRate);

Arrow functions are shorthand for simple one-expression closures and automatically capture outer variables by value — no explicit use() needed — but they can’t contain multiple statements, so full closures are still necessary for anything more complex.