I am learning about static
variables in PHP and came across this code in PHP manual.
<?php
function test() {
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>
I couldn't understand the purpose of last $count--;
. So, I wrote a different version of the function below:
<?php
function test() {
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
echo 'I am here!';
$count--;
}
test();
?>
The output of above code is:
12345678910I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!
Why isn't the output just the line below because we go past the if
condition only once.
12345678910I am here!
If we are going past the if
condition multiple times, then shouldn't the output be:
1I am here!2I am here!3I am here!4I am here!5I am here!6I am here!7I am here!8I am here!9I am here!10I am here!
Thanks.
This is more about recursion than static variables. However:
Why the numbers are written out first and the text afterwards? Let's break each run of the function. For simplification, I'll only use example with 2 calls (if ($count < 2)
)
$count
is incremented to 1
1
$count < 2
is met, so it calls test()
(so that's going to be the 2nd call)$count
is incremented to 2 (if it weren't static, it wouldn't keep the value from the higher scope)
2
$count < 2
is NOT met, so it skips the if
block
I am here!
and ends the 2nd callI am here!
and ends the 1st call