0

What happens when static variable is assigned a value?

In one of the php challenges, the code is something like function something($i=1){static $x = 101; $x-=$i; echo $x;}and this code is called for several times with different arguments. I can understand the property of "static" that it reserves a space which will not be cleaned after being called. But I don't understand why calling something(1) for several times will print 100, 99, 98, etc instead of 100, 100, 100. Isn't that each time the function is called, $x is assigned to 101 again? Thanks!

11th Sep 2017, 5:12 AM
Victor Tang
Victor Tang - avatar
8 ответов
+ 4
@Victor Tang, the static keyword somehow makes the function wherein a variable is declared sort of "remember" the last value of the variable, only the first call to the function assigns 101 to $x, the successive calls will only use the last value that was previousy assigned, like this: // assuming $i = 1 on each call 1st call : $x =101, then $x-=1 (100) 2nd call : $x =100, then $x-=1 (99) 3rd call : $x = 99, then $x-=1 (98) // and it goes on... Hth, cmiiw
11th Sep 2017, 6:54 AM
Ipang
+ 4
Yes, that's what I was trying to explain on my first post, the fist line is executed once, when the function is called for the first time, the next times the function is called only the second line will be executed, the static variable will still have its previous value. Hth, cmiiw
11th Sep 2017, 4:54 PM
Ipang
+ 3
@MobPsycho???, yeah, I was confused at times also, but now I understand "private" is used for declaring private members of a class :) @Victor Tang, cool! you're welcome :)
12th Sep 2017, 2:22 AM
Ipang
+ 2
If what you mean is to reset its value to its initial then I don't know, maybe you can try to change the $i depending on the last value of $x to regain its initial value. e.g. If you know $x = 95, to regain 101 pass -6 as value for $i, so it will be 95-(-6) => 101. Another possibility would be to modify the function, add a parameter, say, $reset, expecting a boolean, then use if .. else block so that when $reset = true, the $x will be reassigned its initial value. function something($i = 1, $reset = false) { static $x = 101; if($reset) { $x = 101; } else { $x -= $i; } return $x; } Hth, cmiiw
11th Sep 2017, 4:08 PM
Ipang
+ 1
So does it mean that for static variables, we can only assign value to it once, and after that we cannot assign another value to it directly?
11th Sep 2017, 3:36 PM
Victor Tang
Victor Tang - avatar
+ 1
function something($i=1){ static $x = 101; // line 1 $x -= 1; // line 2 } I am curious that by calling something() several times, line 1 will not reset the value x to 101, instead only line 2 is executed in each call.
11th Sep 2017, 4:23 PM
Victor Tang
Victor Tang - avatar
+ 1
I get it! Thanks!
12th Sep 2017, 2:09 AM
Victor Tang
Victor Tang - avatar