🐘 PHP Beginner

What are PHP closures (anonymous functions)?

Why Interviewers Ask This

This is a classic screening question for PHP roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

A closure (anonymous function) in PHP is a function without a name that can be assigned to a variable or passed as an argument. $multiply = function(int $a, int $b): int { return $a * $b; };. Closures can capture variables from the outer scope using the use keyword: function($x) use ($multiplier) { return $x * $multiplier; }. To capture by reference: use (&$counter). Closures are objects of the Closure class and have methods like bind() and bindTo(). PHP 7.4 introduced arrow functions (fn($x) => $x * 2) as a short syntax that automatically captures variables from the outer scope without needing use.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.