June 4, 2025

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 the use 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 using use. 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.”