PHP › Closures & Anonymous Functions
What are arrow functions introduced in PHP 7.4, and how do they simplify writing short closures compared to traditional anonymous functions?
IntermediateAnswer
Arrow functions provide a more concise syntax for writing short, single expression closures, automatically capturing variables from the enclosing scope by value without needing an explicit use clause, which significantly reduces boilerplate for simple, common cases like transforming array elements, though they are limited to a single expression and cannot contain multiple statements like a traditional anonymous function can.
$taxRate = 0.08;
$calculateTax = fn($price) => $price * $taxRate;
echo $calculateTax(100);Real-world example A developer refactors a verbose traditional closure with an explicit use clause into a much shorter, single line arrow function, since the surrounding tax rate variable is automatically captured without requiring any extra syntax.