What is a Closure (Anonymous Function) in PHP?
Definition:
A closure is an anonymous function (i.e., a function without a name) that can capture variables from its surrounding scope using theuse
keyword.
β Basic Syntax Example
$message = 'Hello';
$greet = function($name) use ($message) {
return "$message, $name!";
};
echo $greet('Jigang'); // Output: Hello, Jigang!
β Sample Interview Explanation:
βThis is an anonymous function that takes
$name
as a parameter and accesses$message
from the outer scope usinguse
. This is helpful in functional programming, callbacks, or when defining short-lived functionality.β
πΉ Real Interview-Style Examples
1. Sorting with Custom Rule
$users = [
['name' => 'Anna', 'age' => 22],
['name' => 'Ben', 'age' => 18],
['name' => 'Chris', 'age' => 30],
];
usort($users, function ($a, $b) {
return $a['age'] <=> $b['age'];
});
π£οΈ Sample Interview Comment:
βI used a closure to pass a custom sorting logic to
usort
. This allows me to keep the logic self-contained and avoids creating a named function for one-time use.β
2. Using use()
to Capture External Variables
$discount = 0.2;
$applyDiscount = function ($price) use ($discount) {
return $price * (1 - $discount);
};
echo $applyDiscount(100); // Output: 80
π£οΈ Comment:
βThe closure captures
$discount
from outside the function scope and applies it dynamically. This pattern is useful in price calculators or dynamic filters.β
3. Closure as Callback (array_filter)
$prices = [100, 50, 25, 200];
$minPrice = 50;
$filtered = array_filter($prices, function($price) use ($minPrice) {
return $price >= $minPrice;
});
print_r($filtered); // [100, 50, 200]
βI used a closure to filter an array of prices, accessing the
$minPrice
variable from the parent scope.β
πΉ Bonus: Arrow Function Version (PHP 7.4+)
$minPrice = 50;
$filtered = array_filter([100, 40, 60], fn($price) => $price >= $minPrice);
βArrow functions are shorthand closures that automatically capture variables from the parent scope, making them cleaner for small operations.β
π‘ Tip for Interview:
If they ask “When would you use a closure?”, respond with:
βWhen I need to pass around behavior like callbacks, sort rules, filters, or handlers β especially when the logic is short-lived or tightly scoped β closures help reduce boilerplate and improve encapsulation.β
Comments are closed.