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

← All PHP 7 questions