HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Arrow Functions

Introduced in PHP 7.4, arrow functions (also known as short closures) are a more concise way of writing anonymous functions. They are particularly useful for single-line operations and callback functions.


1. The fn() Syntax

An arrow function uses the fn keyword instead of function and is limited to a single expression. It automatically returns the result of that expression.

<?php
    $y = 10;
    
    // Arrow function
    $fn1 = fn($x) => $x + $y;
    
    echo $fn1(5); // Outputs: 15
?>

2. Automatic Scope Capturing

One of the biggest advantages of arrow functions is that they automatically capture variables from the parent scope. In a traditional anonymous function, you would need to use the use keyword to do this.

Comparison: Traditional vs. Arrow

<?php
    $factor = 10;

    // Traditional Anonymous Function
    $multiplySimple = function($n) use ($factor) {
        return $n * $factor;
    };

    // New Arrow Function
    $multiplyArrow = fn($n) => $n * $factor;

    echo $multiplyArrow(5); // Outputs: 50
?>
Value Only: Arrow functions capture variables by **value**, not by reference. This means changing the variable inside the arrow function will not affect the original variable in the parent scope.

3. When to Use Arrow Functions

Arrow functions are best suited for passing small pieces of logic into internal PHP functions like array_map(), array_filter(), or usort().

<?php
    $numbers = [1, 2, 3, 4];
    $squared = array_map(fn($n) => $n * $n, $numbers);
    
    print_r($squared); // [1, 4, 9, 16]
?>
Pro Tip: Use arrow functions to clean up your code when you only have a single mathematical or string operation to perform. It makes your higher-order functions much easier to read.

Key Points to Remember

  • Arrow functions use the fn keyword and the => arrow.
  • They automatically capture variables from the surrounding scope.
  • The result of the expression is returned automatically.
  • They are limited to one single expression (no blocks of code).
  • Arrow functions are available in PHP 7.4+.