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