skip to Main Content

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


  1. 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))

    • 1st call starts, $count is incremented to 1
      • prints 1
    • Within the 1st call, the condition $count < 2 is met, so it calls test() (so that’s going to be the 2nd call)
    • 2nd call starts, $count is incremented to 2 (if it weren’t static, it wouldn’t keep the value from the higher scope)
      • prints 2
    • Within the 2nd call, the condition $count < 2 is NOT met, so it skips the if block
      • prints I am here! and ends the 2nd call
    • Now the 1st call is done running the recursive function so it continues
      • prints I am here! and ends the 1st call
    Login or Signup to reply.
  2. When 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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search