Recursive functions in any language are an essential tool and have a wide variety of uses.
To make a recursive closure in PHP you need to pass the closure variable by reference to the "use" global state of the closure. Here is an example.
$factorial = function($n) use (&$factorial) {
if ($n == 1) {
return 1;
}
return $factorial($n - 1) * $n;
};
print $factorial(5); // Prints 120
If you don't pass the closure by reference then you will essentially pass a null value, since the closure hasn't been defined yet. Passing it by reference means you can use the variable within the closure once it has been created.
Add new comment