PHP Arrow Functions
Arrow functions (PHP 7.4+) provide a shorter syntax for simple
functions. They automatically capture variables from the parent scope - no more
use keyword needed!
Output
Click Run to execute your code
Arrow Function Syntax
<?php
// Traditional
$multiply = function($x, $y) {
return $x * $y;
};
// Arrow function
$multiplyArrow = fn($x, $y) => $x * $y;
?>
Automatic Variable Capture
<?php
$factor = 10;
// No 'use' needed!
$scale = fn($n) => $n * $factor;
echo $scale(5); // 50
?>
Summary
- Syntax:
fn($params) => expression - Auto-capture: No
useneeded - Single expression: Implicit return
- PHP 7.4+: Modern feature
What's Next?
Next, learn about Variadic Functions - handling variable numbers of arguments!
Enjoying these tutorials?