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.
2
Answers
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 11
$count < 2
is met, so it callstest()
(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 theif
blockI am here!
and ends the 2nd callI am here!
and ends the 1st callWhen you’re calling
test()
within the method that doesn’t stop the execution of the rest of the code in the method.The reason, as far as i can see, it doesn’t output a number after each string of "i am here" is because you’re calling the method
test()
before the output. So each time it’s waiting for that method to complete before moving on to the next string.If you were to move the
$count
echo to after it I believe it’d output as expected.Does that answer your question at all?