New course! Every coder should learn Generative AI!
Try a free lesson+ 1
Can someone explain to me how this code works?
<?php function loop(){ static $a = 1; $b = 1; $a++; $b++; return $a.$b; } for($i = 0;$i < 3;$i++) loop(); echo loop(); ?>
3 Answers
+ 5
You can see info about static variables here https://www.tutorialspoint.com/php/php_static_variables.htm.
When a variable is declared static the value is stored after each operation. It's exactly the opposite when the variable is not static. The value is lost on system exit of the function. So in the loop we call the loop function 3 times => the value of "a" becomes 4, the value of "b" is not stored so it becomes 2. After that we call again loop function when printing => "a" is now 5, "b" can't be more than 2 as its value is not stored. At the end concatenate "a" and "b" => 52. You can see the result of the code here
https://code.sololearn.com/w1ok42ja24RG/?ref=app
+ 3
You are welcome :)
0
Thank you so much :D