What is it?
A closure is an anonymous function stored in a variable. An arrow function (PHP 7.4+) is a shorter closure that automatically captures outer variables. Both are essential for working with array functions and callbacks.
Why does it matter?
Closures and arrow functions let you pass behaviour as a value — sort by price, filter active users, transform data — without defining a named function for every small operation.
Understand PHP closures, use() capture, arrow functions, and uses with array functions.
Real-World Use Cases
- 🔍 Filtering products - array_filter with fn($p) => $p['price'] > 500 creates a sub-list of premium products in one line.
- 📊 Data transformation - array_map with fn($row) => $row['total'] * 1.18 applies GST to every row of an orders array.
- 🔀 Custom sorting - usort with fn($a,$b) => $b['rating'] <=> $a['rating'] sorts products by rating descending without a named function.
- 🎯 Event callbacks - Pass a closure to a router or event dispatcher: $router->get('/home', fn() => view('home')).
Closures with use() — Capture Outer Variables
$tax = 18;
$calc = function($price) use ($tax) {
return $price + ($price * $tax / 100);
};
Arrow Functions — Auto Capture, No use()
$tax = 18;
$calc = fn($price) => $price + ($price * $tax / 100);
Practical: array_map, array_filter, usort
array_map()→ Transform each array element.array_filter()→ Keep only matching elements.usort()→ Sort an array using custom logic.
// array_map() - Transform array values
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers);
// array_filter() - Filter array values
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
// usort() - Custom sorting
$users = [
['name' => 'Raj', 'age' => 30],
['name' => 'Amit', 'age' => 25],
['name' => 'Neha', 'age' => 28]
];
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
Q: When should I use an arrow function instead of a closure?
Use arrow functions for short single-expression callbacks — they auto-capture outer variables. Use closures when you need multiple statements, reference capture (&), or the logic is more than one line.
Comments (0)
No comments yet. Be the first!
Leave a Comment