-1

EDIT: I'm sorry for the duplicate, but searching for the title of this question wasn't showing such duplicate in the search result, so I was not aware there is question, already.


This won't work, because $greet is unknown by the time it will be called.

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
    if($name != 'PHP')
    {
        $greet('PHP'); // $greet not defined
    }
};

$greet('World');
?>

The idea is to have a recursive function that is purely in its parent scope (i.e. function in function), without the requirement to build a class.

So, how to build an anonymous recursive function in PHP, properly? Is it even possible? If so, how?

Martin Braun
  • 10,906
  • 9
  • 64
  • 105
  • 3
    Does this answer your question? [Anonymous recursive PHP functions](https://stackoverflow.com/questions/2480179/anonymous-recursive-php-functions) – El_Vanja May 12 '21 at 17:10
  • @El_Vanja Yes, thanks a lot. It wasn't showing up when searching for it using the title of this question. – Martin Braun May 12 '21 at 17:21
  • Small tip: Google search works better for queries constructed as a sentence (copy and paste your question title into it and you'll see). For the internal SO search, it's better to only input the keywords (e.g. `[php] anonymous recursive function`). – El_Vanja May 12 '21 at 19:00

1 Answers1

1

Yes you can. You need to use the $greet variable by reference, like this:

$greet = function($name) use (&$greet)
{
    printf("Hello %s\r\n", $name);
    if($name != 'PHP')
    {
        $greet('PHP');
    }
};

$greet('World');

Working example:
https://3v4l.org/vUhIW

This article describes this a bit more:
https://fragdev.com/blog/php-recursion-with-anonymous-functions

jszobody
  • 28,495
  • 6
  • 61
  • 72