Home > Backend Development > PHP Tutorial > About PHP static variables

About PHP static variables

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-09-19 09:16:34
Original
1042 people have browsed it

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>
Copy after login
Copy after login

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

<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>
Copy after login
Copy after login
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.

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template