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

trusktr picture trusktr · Apr 28, 2011 · Viewed 13k times · Source

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?

Answer

prodigitalson picture prodigitalson · Apr 28, 2011

The simplest thing to do is pass the variable as an argument. I wouldnt really mess with static here.

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

As a general rule you should have to pass the arguments to the function (unless they operate on class properties within the same class)... they shouldnt be global and in the case of recursion its probably not a good idea to make them static... Treat a function like a black box... values go in... they get stuff done with/to them and a result comes out. They shouldnt be aware of things happening elsewhere. There are some exceptions, but IMO they are very few.