Closures in PHP
PHP supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
To run the program, save it as closures.php
and use the PHP CLI:
In PHP, closures are implemented using the Closure
class. When defining an anonymous function, you can use the use
keyword to inherit variables from the parent scope. The &
before $i
in use (&$i)
allows the closure to modify the original variable, not just a copy.
The intSeq
function returns an anonymous function that increments and returns $i
. Each time we call this returned function, it remembers and modifies its own $i
, demonstrating the closure’s state preservation.
By creating a new closure with $newInts = intSeq()
, we show that each closure maintains its own independent state.
The last feature of functions we’ll look at for now is recursion.