如何在递归结束后清除PHP中的静态变量


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

例如,我在递归函数中有一个静态变量,并且我希望该变量在每次递归调用中都是静态的,但是一旦递归结束,我希望该变量被重置,以便下次使用递归函数时它从头开始。

例如,我们有一个函数:
<?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);
}
?>

我们可以像这样第一次调用这个函数:someFunction();,它会工作得很好。然后我们再次调用它:someFunction();,但这次它从$variable的前一个值开始。我们如何在第一次调用函数递归后重置它,以便第二次调用它就像重新开始一样?

最简单的方法是将变量作为参数传递。我不会在这里使用静态。

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

作为一般规则,你应该把参数传递给函数(除非它们在同一个类中的类属性上操作)…它们不应该是全局的,在递归的情况下,将它们设置为静态可能不是一个好主意……把一个函数当作一个黑盒子……价值观…他们把事情交给自己,然后结果就出来了。他们不应该意识到其他地方发生的事情。

prodigitalson的答案是最好的解决方案,但由于您要求使用静态变量的解决方案,我没有看到合适的答案,这里是我的解决方案。

完成后将静态变量设置为null。下面将在两个调用中打印12345。

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

或者用一个初始化式把这个和前面的答案结合起来:

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);

将输出:

345
45
12345
-1012345

好吧,我看到prodigitalson把答案藏在我身上了。下面是一个演示:

http://codepad.org/4R0bZf1B

<?php
function someFunction($varset = NULL) {
    static $variable = NULL;
    if ($varset !== NULL) $variable = $varset;
    $variable++;
    echo $variable;
    if ($variable < 5) someFunction();
    return $variable;
}
someFunction(4);
echo "'n";
someFunction(2);
echo "'n";
someFunction(3);
?>

输出:

5
345
45

您可以使用$depth计数器:

function someFunction() {
    static $variable = null, $depth= 0;
    $depth++;
    do stuff; change value of $variable; do stuff;
    someFunction(); # The value of $variable persists through the recursion.
    $depth--;
    $temp = $variable;
    if($depth== 0){
        $variable = null;
    }
    return ($temp);
}

我找到了一个解决方案:

<?php
function someFunction($clear_static = false) {
    static $variable = null;
    if ($clear_static) {
        $variable = null;
    }
    do stuff; change value of $variable; do stuff;
    someFunction(); # The value of $variable persists through the recursion.
    return ($variable);
}
someFunction(); # first manual call.
someFunction(); # second manual call, $variable has value from previous use.
someFunction(true); # third manual call, value of $variable starts like new.
?>