PHP Approves Short Arrow Functions

Short Arrow Functions

Loading

The PHP team recently approved the Short Arrow Functions RFC proposed by Nikita Popov, Levi Morrison, and Bob Weinand.

In the RFC it shows this as an example to give you an idea on how it can be used:

$extended = function ($c) use ($callable, $factory) {
    return $callable($factory($c), $c);
};
 
// with arrow function:
// Appfinz Technologies 
$extended = fn($c) => $callable($factory($c), $c);

 A Laravel example could look like this: 

// Current
$users->map(function($user) {
    return $user->first_name.' '.$user->last_name;
});

// with arrow function:
// appfinz Technologies 
$users->map(
    fn($user) => $user->first_name.' '.$user->last_name
);

✅ Latest on PHP Short Arrow Functions

1. Syntax Simplification (PHP 7.4+)
PHP introduced short arrow functions in version 7.4 to reduce verbosity when writing closures.

// Traditional anonymous function
$double = function ($x) {
    return $x * 2;
};

// Short arrow function
$double = fn($x) => $x * 2;

2. Implicit use Handling
Short arrow functions automatically capture variables from the parent scope — unlike traditional closures where you need use() explicitly.

$multiplier = 3;

// Short arrow captures $multiplier automatically
$triple = fn($x) => $x * $multiplier;

3. Single Expression Limitation
Short arrow functions only support a single expression — no blocks, conditionals, or multiple statements.

// ✅ Valid
$sum = fn($a, $b) => $a + $b;

// ❌ Invalid - cannot use multiple statements or blocks
// $func = fn($x) => { $y = $x + 1; return $y; };

4. Use Cases Growing in Modern PHP
They’re now widely used in:

  • Laravel collections
  • Functional programming patterns
  • Array mapping/filtering
$data = [1, 2, 3, 4];
$filtered = array_filter($data, fn($n) => $n % 2 === 0);

5. Performance & Readability
They are not faster, but significantly improve code clarity and brevity, especially in inline functions.

📌 Summary

PHP short arrow functions (fn() =>) are great for cleaner, simpler, and modern-looking code. They automatically inherit scope variables and are ideal for one-liners, making PHP more competitive with modern functional paradigms seen in JavaScript, Python, etc.

If you’re using PHP 7.4 or newer, it’s highly recommended to adopt them wherever applicable — especially in array operations, callbacks, and simple logic.

About Post Author