PHP static variables

Source: Internet
Author: User
Isn't the static variables of PHP stored only in one copy? I tried the following code today. I have some doubts: {code...} since it is only a copy in the memory, calling it again is similar to direct reference. why is $ num assigned 20 for the first time? Shouldn't the result of the first running be 4950? isn't the static variable of PHP saved only in one copy? I tried to explain the following code today.

function test(){    static $sum = 0;    static $sum = 20;    for ($i=0; $i < 100; $i++) {         $sum = $sum + $i;     }    echo  $sum;}echo "
";    test();//4970echo "
"; test();//9920echo "
"; test();//14870

Since there is only one copy in the memory and the re-call is similar to direct reference, why is $ num assigned 20 for the first time?
The first running result should not be 4950.

Reply content:

Isn't the static variables of PHP stored only in one copy? I tried to explain the following code today.

function test(){    static $sum = 0;    static $sum = 20;    for ($i=0; $i < 100; $i++) {         $sum = $sum + $i;     }    echo  $sum;}echo "
";    test();//4970echo "
"; test();//9920echo "
"; test();//14870

Since there is only one copy in the memory and the re-call is similar to direct reference, why is $ num assigned 20 for the first time?
The first running result should not be 4950.

$ I = 1; $ I <101
...

// Result: 4950;

It can be understood as the row with the value of 20. it overwrites the row with the upper face value of 0. because the variable names are the same, the initialization time is 20.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.