+ 1
Why does this code output "10099100"? What exactly does "static" in PHP mean?
Given the code from a challenge below: function f($i=1){ static $id = 101; $id -= $i; echo $id; } f(); f(1); f(-1); result is: 10099100 but why? When I go through it the result should be as follows: 101 - 1 = 100 101 - 1 = 100 101 - (-1) = 102 => 100100102 I don't get it 😟
3 Respostas
+ 2
Since $id is static, when you make a change to it, it will remain. The function will not recreate the static variable $id if it already exists, but alter it from its previous state.
https://stackoverflow.com/questions/6188994/static-keyword-inside-function
http://php.net/manual/en/language.oop5.static.php
So the first time through the function the variable is created and its value is set to 101.
Then the default value of 1 is subtracted from it and saved back into it making the output value 100.
The second time through the variable is already set and exists so it is not recreated and already has the value of 100. The passed value of 1 is subtracted from it and it is saved and output as 99.
Then the third time through the value of -1 is used which increases the value back to 100.
+ 3
this is work like that
first function f($i=1)
this function body works when $i=1th
static $id=101;
static means the I'd can change during the program execution
$id-=$I;
so 101-1=100. this is first output when function f() is called
then $I become $i=100
then during call of function f(1)
$id-=$I;
which become $id=100-1
$id=99. second output after that
during call of f(-1)
$id-=$I; which become
$id=99-(-1)=>99+1
$id=100. third output
so finally the output is
10099100
0
Thank you both for the answers. Again I learned something.
@ChaoticDawg: very good explanation, thanks.
Does "static" mean that I can declare a variable in a PHP script in a file, for example "$var" within "static.php", and that variable will remain and keep its value?