How to create an anonymous (Closure) recursive function?

Asked

Viewed 231 times

3

In php, we can create recursive functions as follows.

function quack($quack = 1)
{

    if ($quacks >= 1) {
      echo "Quack";
      $quack--;
      quack($quacks);
    }
}

Or, in case of avoiding problem with "renaming" the function.

function quack($quack = 1)
{ 

   $func = __FUNCTION__;

    if ($quacks >= 1) {
      echo "Quack";
      $quack--;
      $func($quacks);
    }
}

But, and when it comes to anonymous functions?

Example:

$quack = function ($quacks)
{
   if ($quacks >= 1) {
      echo "Quack";
      $quacks--;
       // como chamo $quack aqui?
   }
}

How could I make the function anonymous $quack in a recursive function?

  • Let’s see if someone kills this charade :)

1 answer

5


Simply assign your anonymous function to a variable and pass this variable by reference.

Take for example an anonic function that calculates the factorial of a value:

$factorial = function($n) use(&$factorial) {
    if ($n == 1) return 1;
    return $factorial($n - 1) * $n;
};

So we call this function by means of the variable to which it is assigned:

print $factorial(4); // 24

I saw in Soen’s reply: https://stackoverflow.com/questions/2480179/anonymous-recursive-php-functions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.