Closures & Callbacks
Prerequisites: Regular expressions
A closure is a full anonymous function — unlike an arrow function
(Level 1), it must explicitly capture outer variables with use:
$tax = 0.2;
$addTax = function ($price) use ($tax) {
return $price * (1 + $tax);
};
echo $addTax(100); // 120
Passing use (&$tax) (by reference) lets the closure see later
changes to $tax, rather than a snapshot from when it was created.
Common mistakes
- Forgetting
use (...)and expecting an outer variable to be visible inside a closure — unlike an arrow function, a closure captures nothing automatically.