Closures
A function without a name captures a value through use.
An anonymous function is a value. You put it into a variable and pass it to usort or array_map. The syntax is function ($x) { return $x + 1; } or the short arrow fn($x) => $x + 1.
An ordinary anonymous function does not see outside variables. You list them in use ($step). Capturing by value copies the number at creation time. Later the outer $step may change, but the old one stays inside. A reference use (&$step) sees changes and is rarely needed.
An arrow fn captures variables by value on its own. Its body is a single expression. If you need two lines and a condition, write an ordinary anonymous function, not a heroic arrow.
A closure that drags half the request along is hard to test. Capture one number or one string. In the task a step is added to the argument: a factory returns a function, and the check calls it.
Practice
Why use
Why does an anonymous function not see an outside variable on its own?
- It sees everything on its own
- You need use or an arrow fn
- You always need global
- You need echo
The arrow
What number does fn($x) => $x + 1 return when called with 2?
Add a step
Write function adder($step). Return an anonymous function that takes $n and returns $n + $step.