Arrow Functions

PHP arrow functions, introduced in PHP 7.4, provide a more concise syntax for anonymous functions. They are particularly useful for short callbacks. Here’s a quick overview:

Syntax

An arrow function uses the fn keyword and has a simplified syntax:

$sum = fn($a, $b) => $a + $b;
echo $sum(2, 3); // Outputs: 5

Key Features

  1. Implicit Return: Arrow functions automatically return the result of the expression without needing the return keyword.
  2. Variable Scope: They automatically capture variables from the surrounding scope (lexical scoping), meaning you don’t need to use the use keyword.

Example

Here’s an example of using an arrow function with the array_map function:

$numbers = [1, 2, 3, 4];
$squared = array_map(fn($n) => $n ** 2, $numbers);
print_r($squared); // Outputs: [1, 4, 9, 16]

Limitations

  • Arrow functions can only contain a single expression. If you need more complex logic, you’ll have to use a traditional anonymous function.

Leave a Reply

Your email address will not be published. Required fields are marked *