0
How do PHP static keyword work?
I'm not sure when should I use the static keyword and I don't know where can I use that. I found the below code example in a PHP challenge - function myFunction($i=1) { static $id = 101; $id -= $i; echo $id; } myFunction(); echo"\n"; myFunction(1); echo"\n"; myFunction(-1); // output = 100 99 100 I didn't Google for it. I want to learn this from SoloLearn family 💜
1 Resposta
+ 2
The PHP keyword static in functions allows you to define a variable which will maintain its value every time you call that function.
The first time $id is assigned to 101 and then the function subtracts 1 ($id is now 100).
The second time $id is already assigned (100), so the static assignment is ignored and the function subtracts again 1 ($id is now 99).
The third time $id is 99 and the function subtracts -1, thus adding 1 ($id is now 100).