Creating A Recursive Closure In PHP

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

The content of this field is kept private and will not be shown publicly.
17 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.