如何在PHP中销毁静态变量?

时间:2019-01-04 03:46:22

标签: php recursion static

this question的回答说unset()不起作用,但不清楚作用是什么。我有一个使用静态变量的递归函数,但是在递归完成并返回值之后,我需要重置那些变量,否则后续调用(当前在循环内调用了递归函数)将返回错误的值。

在链接的问题中,有人建议在我执行的功能之外尝试$var = NULL,但似乎没有效果。

我之所以使用静态变量,而不仅仅是将其作为函数的参数编写,是因为我不希望出现用户可以将参数传递给该函数的情况,因为函数的唯一参数应该从内部提供。


我的代码

<?
    require_once("randX.php");  #"randX()" generates a random floating point number in a specified range.
    // require_once("../displayArray.php");  
    error_reporting(E_ERROR | E_WARNING | E_PARSE);

/*
*   Generates a valid, random probability distribution for a given array of elements, that can be used in conjunction with "probSelect()".
*   Input: 
        $arr: An array of elements.
        $control: A value that decides how much mass is allowed to be unilaterally dumped onto one element. A high value would permit distributions where most of the mass is concentrated on one element. 
        If an invalid value is provided, the default is used.
*   Output: An associative array where the keys are the elements in the original array, and the values are their probabilities. 
*   @param array $arr:  An array of elements for which the probability distribution would be generated. 
*   @param float $control: A variable which limits the inequality of the probability distribution.
*/
    function probGen(array $arr, float $control = 0.01) 
    {
        $control = ($control <= 1 && $control >= 0)?($control):(0.00001);   #Use the default value if an invalid number is supplied.
        static $result = [];    #Initialises $result with an empty array on first function call.
        static $max = 1;    #Initialises $max with 1 on first function call.
        foreach ($arr as $value) 
        {
            $x = randX(0, $max);    #Random probability value.
            $result[$value] = ($result[$value] + $x)??0;    #Initialise the array with 0 on first call, and on subsequent calls increment by $x to assign probability mass.
            $max -= $x;     #Ensures that the probability never sums to more than one.
        }
/*
*   After the execution of the above code, there would be some leftover probability mass. 
*   The code below adds it to a random element.
*/
        $var = array_values($arr);
        if($max <= $control)    #To limit concentration of most of the probability mass in one variable.
        {
            $result[$var[rand(0,(count($var)-1))]] += $max; #Selects a random key and adds $max to it.
            // print("<br>Sum: ".array_sum($result)."<br>");
            return $result;
        }
        else
        {
            return probGen($arr, $control); 
        }
    }
    $max = NULL;        
    unset($max);
    $result = NULL; 
    unset($result);
?>

1 个答案:

答案 0 :(得分:0)

在任何情况下使用static始终是问题,我将其更改为要传入的参数并具有默认值...

function probGen(array $arr, float $control = 0.01, $result = [], $max = 1 ) 

(具有适当的类型)。

然后可以在您进一步的呼叫中将它们传递到链下...

return probGen($arr, $control, $result, $max);

这可以让您更好地控制这些值的开头(您可以默认传入您自己的值),也可以在通话中重置/调整它们。