Skip to content

Instantly share code, notes, and snippets.

@MarcelloDuarte
Created April 9, 2013 07:13
Show Gist options
  • Save MarcelloDuarte/5343629 to your computer and use it in GitHub Desktop.
Save MarcelloDuarte/5343629 to your computer and use it in GitHub Desktop.
Even wondered how to use recursion in PHP closures?
<?php
$decrease = function($self, $number) {
if ($number >= 0) {
echo $number . PHP_EOL;
$self($self, --$number);
}
};
$decrease($decrease, 10);
@MarkBaker
Copy link

In a similar vein, using use

<?php

$cnt = 5;

$f = function() use(&$cnt, &$f) {
    echo $cnt--,PHP_EOL;
    if ($cnt > 0)
        $f();
};

$f();

I think the use of use for the closure itself is probably cleaner because I don't then have to remember to pass the closure as an argument to itself every time I call it; though the $number value for this simple decrementer should really be passed as a standard argument in the initial call

@MarcelloDuarte
Copy link
Author

Mark Baker pointed out you can pass the closure (as reference) in the use clause, making it more user friendly.

<?php

$decrease = function($number) use (&$decrease) {
    if ($number >= 0) {
        echo $number . PHP_EOL;
        $decrease(--$number);
    } 
};

$decrease(10);

@MarcelloDuarte
Copy link
Author

oops, added my comment before refreshing the page :)

@MarkBaker
Copy link

But you've cleaned up my example, by passing $number as a simple argument :)

@liuggio
Copy link

liuggio commented Apr 9, 2013

:) and changing decrease inside decrease?

nightmare version

$decrease = function($number) use (&$decrease) {
    $oldDecrease = $decrease;
    $rand = rand($number/2, $number*2);
    if ($number !=  $rand) {
        echo $number . PHP_EOL;
        $decrease(--$number);
    } else {
        $decrease = function($number) use (&$decrease, &$oldDecrease) {
            $rand = rand($number/2, $number*2);
            if ($number ==  $rand) {
                echo $number . PHP_EOL;
                $decrease(--$number);
            } else {
                $oldDecrease($number*2);
            }
        };
    }
};

$decrease(10);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment