Search code examples
phprecursionstatic-variables

How do you clear a static variable in PHP after recursion is finished?


So for example, I have a static variable inside a recursive function, and I want that variable to be static through out each call of the recursion, but once the recursion is finished, I want that variable to be reset so that the next time I use the recursive function it starts from scratch.

For example, we have a function:

<?php
function someFunction() {
    static $variable = null;
    do stuff; change value of $variable; do stuff;
    someFunction(); # The value of $variable persists through the recursion.
    return ($variable);
}
?>

We can call the function for the first time like this: someFunction(); and it will work fine. Then we call it again: someFunction(); but this time it starts with the previous value for $variable. How can we reset it after the recursion of the first time we called the function so that the second time we call it it is like starting over fresh?


Solution

  • Prodigitalsons answer is the best solution, but since you asked for a solution using static variables and I don't see an appropriate answer here's my solution.

    Just set the static variable to null when you're done. The following will print 12345 on both calls.

    function someFunction() {
        static $variable = 0;
        $variable++;
        echo $variable;
        if ($variable < 5) someFunction();
    
        $returnValue = $variable;
        $variable = null;
        return $returnValue;
    }
    someFunction();
    echo "\n";
    someFunction();
    echo "\n";
    

    Or combine this with the previous answer with an initializer:

    function someFunction($initValue = 0) {
        static $variable = 0;
        if($initValue !== 0) {
            $variable = $initValue;    
        }
        $variable++;
        echo $variable;
        if ($variable < 5) someFunction();
    
        $returnValue = $variable;
        $variable = null;
        return $returnValue;
    }
    
    someFunction(2);
    echo "\n";
    someFunction(3);
    echo "\n";
    someFunction();
    echo "\n";
    someFunction(-2);
    

    Will output:

    345
    45
    12345
    -1012345