Don’t PHP’s static variables only store one copy in memory? I tried the following code today and I have some questions
<code>function test(){ static $sum = 0; static $sum = 20; for ($i=0; $i < 100; $i++) { $sum = $sum + $i; } echo $sum; } echo "<pre class="brush:php;toolbar:false">"; test();//4970 echo "<br />"; test();//9920 echo "<br />"; test();//14870 </code>
Since there is only one copy in the memory, calling it again is similar to a direct reference, so why was $num assigned to 20 for the first time?
Shouldn’t the result of the first run be 4950?
<code>function test(){ static $sum = 0; static $sum = 20; for ($i=0; $i < 100; $i++) { $sum = $sum + $i; } echo $sum; } echo "<pre class="brush:php;toolbar:false">"; test();//4970 echo "<br />"; test();//9920 echo "<br />"; test();//14870 </code>
Shouldn’t the result of the first run be 4950?
…
//Result: 4950;
It can be understood that the line with the value 20 overwrites the line with the value 0 above. Because the variable names are the same, it is 20 when initialized.