Technical Mid Level

How do closures and first-class callables work in PHP? How have they evolved from PHP 5.3 to PHP 8.1, and when do you prefer them over class-based approaches?

Quick Tip

Show the evolution: "PHP 5.3 closures needed use() for every variable. Arrow functions capture automatically. First-class callables in 8.1 let me pass strlen(...) directly instead of wrapping it. Each step reduced boilerplate."

What good answers include

Closures (anonymous functions) arrived in PHP 5.3 with use() for variable binding. Short closures (arrow functions, fn() =>) came in PHP 7.4 with automatic variable capture and single-expression bodies. First-class callable syntax ($object->method(...)) arrived in PHP 8.1, replacing Closure::fromCallable(). Use closures for: callbacks, array_map/array_filter, event handlers, and small scoped logic. Prefer class-based approaches when: the logic is complex, needs testing in isolation, or is reused across multiple contexts. Strong candidates discuss: Closure::bind() and Closure::call() for rebinding $this, the performance characteristics of closures versus invokable classes, and that arrow functions solve the common annoyance of use($var) for simple callbacks.

What interviewers are looking for

Tests language fluency. Candidates stuck on PHP 5.x closure syntax are not using modern features. Those who understand the full evolution and can choose between closures and classes based on complexity demonstrate practical language mastery.

← All PHP questions