Home > Article > Backend Development > About PHP static variables
Don’t PHP’s static variables only store one copy in memory? I tried the following code today and I have some questions
function test(){
static $sum = 0;
static $sum = 20;
for ($i=0; $i < 100; $i++) {
$sum = $sum + $i;
}
echo $sum;
}
echo "";
test();//4970
echo "
";
test();//9920
echo "
";
test();//14870
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?
function test(){
static $sum = 0;
static $sum = 20;
for ($i=0; $i < 100; $i++) {
$sum = $sum + $i;
}
echo $sum;
}
echo "";
test();//4970
echo "
";
test();//9920
echo "
";
test();//14870
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?
…
//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.