PHP – Doing Recursion in Anonymous Functions / Closures

If you’re trying to use a PHP anonymous function recursively and are having trouble, you might be seeing an error like

Notice: Undefined variable: fooFunction in /yourScript.php on line 10

This error can result from one of [at least] two problems:

Not Using The Function Variable

Take at look at line in your script where the “undefined variable” error is being thrown. If it’s line where the recursive call is made, then this is your problem.

What you need to do is use the use keyword in your function declaration and mention the function variable itself. Take a look at #2 and the example below to see how to do this correctly.

Failure to Pass the Function Variable By Reference

If the “undefined variable” error in your script is being throw on the function declaration line and you are using the use keyword, then this is probably your issue.

What you need to do is add an ‘&’ symbol in the use parenthesis ahead of your function name to pass the function by reference. If you fail to pass by reference, the function variable will take on it’s value (most-likely NULL) before the function was declared.


Take a look at the script below. Look for the use keyword and the ‘&’ symbol.

$killTheCat = function($lives = 9) use (&$killTheCat) {
$lives--;
echo 'Running, ';
if ($lives > 0) {
echo 'lives = '.$lives.'!'.PHP_EOL;
$killTheCat($lives);
} elseif ($lives <= 0) {
echo 'lives == 0 and the cat is dead.'.PHP_EOL;
}
};

$killTheCat();
/**
* Running, lives = 8!
* Running, lives = 7!
* Running, lives = 6!
* Running, lives = 5!
* Running, lives = 4!
* Running, lives = 3!
* Running, lives = 2!
* Running, lives = 1!
* Running, lives == 0 and the cat is dead.
*/

Leave a Reply

Your email address will not be published. Required fields are marked *

*