How to create a recursive anonymous function (Closure)?

3

In php, we can create functions with recursion as follows.

function quack($quack = 1)
{

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

Or, in case of avoiding problem with "renames" function.

function quack($quack = 1)
{ 

   $func = __FUNCTION__;

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

But what about anonymous functions?

Example:

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

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

    
asked by anonymous 28.07.2015 / 17:57

1 answer

5

Just assign your anonymous function to a variable and pass that 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;
};

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

print $factorial(4); // 24

I saw this response from SOEn: link

    
28.07.2015 / 18:07