Home  >  Article  >  Backend Development  >  About PHP static variables

About PHP static variables

WBOY
WBOYOriginal
2016-09-19 09:16:34900browse

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?

Reply content:

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?

$i =1;$i<101


//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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn