PHP Arrow Functions
In this page:
What are Arrow Functions? (PHP 7.4+)
Introduced in PHP 7.4, arrow functions use the fn keyword and are limited to a single expression, whose result is returned automatically — there's no explicit return keyword, and no curly-brace body, which is what makes them so much shorter than a standard anonymous function for simple cases.
Example: What are Arrow Functions? (PHP 7.4+)
<?php
$double = fn($x) => $x * 2;
echo $double(5);
?>
Login to try C/C++/Java/PHP code in the editor
Implicit Value Binding
Unlike a regular anonymous function, an arrow function automatically captures any variable from its surrounding scope that it actually references — by value — with no use clause needed. This implicit capture is the main practical difference from a standard closure.
Example: Implicit Value Binding
<?php
$tax = 0.1;
$addTax = fn($price) => $price + ($price * $tax);
echo $addTax(100);
?>
Login to try C/C++/Java/PHP code in the editor
Arrow Functions as Callbacks
Because arrow functions are so compact, they read naturally as an inline argument to something like array_map() or usort() — the entire callback fits on the same line as the function call that needs it, without a separate multi-line closure definition above.
Example: Arrow Functions as Callbacks
<?php
$numbers = [1, 2, 3, 4];
$doubled = array_map(fn($n) => $n * 2, $numbers);
print_r($doubled);
?>
Login to try C/C++/Java/PHP code in the editor
Typing Arrow Functions
You can add parameter and return type declarations to an arrow function exactly as you would to any other function — fn(int $x): int => $x * 2 — so the brevity of the syntax doesn't come at the cost of giving up type safety.
Example: Typing Arrow Functions
<?php
$double = fn(int $x): int => $x * 2;
echo $double(5);
?>
Login to try C/C++/Java/PHP code in the editor
Arrow Functions vs Anonymous Functions
The tradeoff for an arrow function's compactness is that it can only contain a single expression — no loops, no multiple statements, no intermediate variables. Anything beyond that single expression requires falling back to a standard anonymous function instead.
Example: Arrow Functions vs Anonymous Functions
<?php
$sum = fn($a, $b) => $a + $b;
echo $sum(2, 3);
// A multi-statement version would need a regular function instead
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: