🐘 PHP Beginner

What are PHP closures (anonymous functions)?

Answer

A closure (anonymous function) in PHP is a function without a name that can be assigned to a variable or passed as an argument. $multiply = function(int $a, int $b): int { return $a * $b; };. Closures can capture variables from the outer scope using the use keyword: function($x) use ($multiplier) { return $x * $multiplier; }. To capture by reference: use (&$counter). Closures are objects of the Closure class and have methods like bind() and bindTo(). PHP 7.4 introduced arrow functions (fn($x) => $x * 2) as a short syntax that automatically captures variables from the outer scope without needing use.