Arrow Functions in PHP

PHP 7.4 version has introduced arrow functions, which provides a concise and shorter syntax to define anonymous functions.

Arrow functions automatically capture variables from the parent scope by value, making using closures easier and cleaner.

The general syntax to define an arrow function in PHP is as follows:

fn(parameters) => expression;

In the above of syntax of arrow function, fn is a keyword which is used to define an arrow function. The fn keyword is followed by the parameters inside the parentheses, which must be a comma-separated list of parameters.

Next, the arrow operator comes, which separates the parameters from the expression. The expression represents the body of the function, which must be a single expression that gets returned automatically.

Key Features of Arrow Functions


There are the following key features of arrow functions that you should keep in mind. They are as:

1. Implicit Return

  • Arrow functions automatically return the result of their single expression, making them more concise.

2. Automatic Variable Capture

  • Arrow functions capture variables from the parent scope by value, simplifying the syntax compared to traditional closures.

3. Single Expression Body

  • The body of an arrow function must be a single expression. If your function logic is complex, you need to use traditional closures instead.

Examples of Arrow Functions in PHP


Let’s take some simple examples of using an arrow function in PHP.

Example 1:

<?php
$add = fn($a, $b) => $a + $b;
$sub = fn($x, $y) => $x - $y;

echo $add(5, 10) . "\n";
echo $sub(10, 5);
?>
Output:
      15
      5

In this example, the $add function takes two parameters named $a and $b and returns the sum of them. Similarly, the $sub function takes two parameters named $x and $y and returns the subtraction of them.


Example 2:

<?php
$factor = 20;
$multiply = fn($num) => $num * $factor;
echo $multiply(10);
?>
Output:
    200

In this example, the $multiply function takes a single formal parameter named $num and returns the product of $num and $factor. Here, the $factor variable is not a parameter of the function, but is a variable of parent scope that is automatically captured by the arrow function.

Use of Arrow Function in Array


Generally, we often use arrow functions when working with PHP arrays. Let’s take some practical examples based on the use of arrow functions in arrays.

Example 3: Filtering an array

<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8];
$evenNumbers = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($evenNumbers);
?>
Output:
      Array
     (
        [1] => 2
        [3] => 4
        [5] => 6
        [7] => 8
     )

In this example, the arrow function fn($n) => $n % 2 === 0 is passed to the array_filter() function. This arrow function is applied to each element of the $number array. It checks whether the element is even.


If the number is even, then returns true. Next, the array_filter() function creates a new array containing only the elements for which the arrow function returned true, resulting in a new array of even numbers.

Example 4: Mapping an Array

<?php
$numbers = [10, 20, 30, 40, 50];
$squaredNumbers = array_map(fn($n) => $n * $n, $numbers);
print_r($squaredNumbers);
?>
Output:
      Array
     (
        [0] => 100
        [1] => 400
        [2] => 900
        [3] => 1600
        [4] => 2500
     )

Example 5: Sorting an Array

<?php
$names = ['John', 'Alice', 'Bob', 'Saanvi'];
usort($names, fn($a, $b) => strlen($a) <=> strlen($b));
print_r($names);
?>
Output:
      Array
     (
        [0] => Bob
        [1] => John
        [2] => Alice
        [3] => Saanvi
     )

These examples show how can you use PHP arrow functions in an array to simplify the code and increase readability.

Common Errors


1. Multi-line Body: Arrow functions cannot have a multi-line body. Attempting to do so will result in a syntax error:

<?php
// Incorrect use.
$greet = fn($name) => {
    return "Hello, $name!";
};
?>

You can use an anonymous function for multi-line logic like this:

<?php
$greet = function($name) {
   return "Hello, $name!";
};
echo $greet("Saanvika");
?>
Output:
      Hello, Saanvika!

2. Variable Capture Issues: Arrow functions capture variables by value.

<?php
$count = 1;
$increment = fn() => $count++;
echo $increment();
?>
Output:
     1

In this example, the variable $count remains 1 because it is captured by value. If you need to modify a captured variable, use an anonymous function or closure with the use keyword like this:

<?php
$count = 1;
$increment = function() use (&$count){
    $count++;
};
$increment(); // Calling function.
echo $count;
?>
Output:
      2

Nested Arrow Functions in PHP


PHP allows you to nest arrow functions. It is necessary to maintain readability. Let’s take an example on it.

Example 6:

<?php
$calculate = fn($x) => fn($y) => $x + $y;
$add = $calculate(5);
echo $add(10);
?>
Output:
      15

Using Arrow Functions in Classes


You can use arrow functions inside the class method. Let’s see an example on it.

Example 7:

class Calculator {
   private $multiplier;

   public function __construct($multiplier) {
      $this->multiplier = $multiplier;
   }

   public function multiply() {
      return fn($number) => $number * $this->multiplier;
   }
}

$calc = new Calculator(10);
$multiply = $calc->multiply();
echo $multiply(2);
?>
Output:
       20

When not to Use Arrow Functions?


(1) If you are dealing with complex logic, use anonymous or named functions for readability.

(2) If you need to modify a variable from the parent scope, use closures with use keyword.

(3) Arrow functions are not suitable for multi-line logic.


Arrow functions are a powerful feature in PHP that simplifies the syntax for anonymous functions. They are especially useful when you are dealing with callbacks, array manipulation, and short utility functions. By understanding arrow functions, you can write cleaner, and more concise PHP code.