PHP Function Reference Call problem

Source: Internet
Author: User
function &test () {
static $b = 1;
$b + = 2;
return $b;
}
$a = &test ();
$a = 8;
$c = &test (); Here again, call the test () function, why the static $b = 1 is no longer executed; Because the result shows that at this time $c=10.
If static is removed, the result is 3. How do you explain this? Thank you!
Echo $c;


Reply to discussion (solution)

Static modifies the variable $b, then it is always there, removing the static, then each call will be initialized once
Because $ A = &test (), (Add &, address pass) so $ A is changed, then the value of the static variable $b is also changed, so when the $c = &test () is executed, the value of $b at this time is 8, which returns 10

Static modifies the variable $b, then it is always there, removing the static, then each call will be initialized once
Because $ A = &test (), (Add &, address pass) so $ A is changed, then the value of the static variable $b is also changed, so when the $c = &test () is executed, the value of $b at this time is 8, which returns 10


Change the statement into
function &test () {
static $b = 1;
static $b = 100;
static $b = 1000;
$b = 1000;
$b + = 2;
return $b;
} and tested again, the original static can no longer be used to modify it in a static way. But do not error, a little unbearable, hehe ~.

Static variables only assign initial values when declaring, static variables have the properties of global variables, but different scopes

Static variables exist only within the scope of the function, that is, the static variables only live in the stack. General function variables are released after the function ends, such as local variables, but static variables do not. That is, the value of the variable is preserved the next time the function is called.

Static variables only assign the initial value when declaring, static variables have the properties of global variables, but the scope is different +1

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