PHP 7 interview question · Most asked
What are arrow functions in PHP 7.4 and how do they differ from closures?
Summary
Arrow functions fn($x) => expr are single-expression closures that automatically capture outer variables by value, with no use clause needed.
Longer Answer
They're ideal for short callbacks in array_map, array_filter and usort. Limitations: one expression only (no statements), and captured variables are by value, so they can't modify outer variables. They also auto-bind $this in class context (use static fn to avoid that).
Code Example
<?php
$factor = 3;
$tripled = array_map(fn($n) => $n * $factor, [1, 2, 3]); // [3, 6, 9]
// Equivalent closure:
$tripled = array_map(function ($n) use ($factor) { return $n * $factor; }, [1, 2, 3]);
Key Points
fn($x) => $x * $factor- Auto-capture by value
- Single expression only
- Can't mutate outer variables
More most-asked PHP 7 questions
- What are typed properties in PHP 7.4?
- How do return type declarations work in PHP 7?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain scalar type declarations and coercive vs strict mode in PHP 7.
- Explain the `Throwable`, `Error` and `Exception` hierarchy introduced in PHP 7.
- What are nullable types in PHP 7.1?
- What does the null coalescing operator `??` do, and how is it different from `isset()` with a ternary?
- What are the main breaking changes when upgrading from PHP 7.4 to 8.0?