Geoff Garbers

Husband. Programmer. Tinkerer.

Recursive anonymous functions in PHP

Jan 24, 2014

Now that anonymous functions have been available since PHP 5.3, I find myself making use of them quite often. However, the one thing that I couldn’t seem to get right was being able to make an anonymous function reference itself - in so doing, calling itself recursively.

How do you do this? Like so:

$func = function ($level = 0) {
    echo str_repeat(' ', $level) . "I am on level {$level}\n";
};
$func();
$func(1);
$func(2);
$func(3);

This becomes tedious to call over & over (it could be placed in a for loop to accomplish the same thing - but this is just a simplistic example). So, how do we implement this as an anonymous function that calls itself recursively? There are two things that need to take place for this to happen:

  1. Ensure that the recursive of the anonymous function is limited in some way. This prevents itself from being called in an infinitely recursive manner (and so bringing your server to its knees).
  2. Start to make use of the use keyword.

The solution

For the anonymous function to be able to call itself recursively, we need to ensure that it has a reference to itself that it is able to call. Thus, our solution, which makes use of a closure:

$maximum = 5; // This can be adjusted to as many levels as necessary.
$func = function($level = 0) use ($maximum, &$func) {
    echo str_repeat(' ', $level) . "I am on level {$level}\n";
    if ($level < $maximum) {
        $func($level + 1);
    }
};
$func();

A final note

Notice how the function references itself - using a variable reference. Why is this necessary?

As the $func variable is being used in the declaration of the anonymous function, it is not yet populated at declaration time. Passing it as a reference, we are able to ensure that by the time the function is executed, the $func variable would have been populated with our anonymous function.