user11555842
user11555842

Reputation: 31

How to deal with a static variable in php

I am a beginner with php and want to understand how static variables work. I have a function that contains a constant variable which is "$ count". When I call the function more than once, the static variable is initialized with "0" in each call. I want to call this function several times keeping in mind that the last value reached by the constant variable is kept.

$x = 2; $y = "Level";

function hello(){
    global $x; global $y;
    static $count = 1;
    for(;;){
        if($count == 11)
            break;
        echo"/hello student_".$count." ".$y."_".$x,"<br>";
        $count++;
    }
}
hello();
hello();
hello();

Upvotes: 1

Views: 48

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94662

If you slightly rearrange you tests, you will better see whats happening

$x = 2; $y = "Level";

function hello(){
    global $x; global $y;
    static $count = 1;
    for(;;){
        if($count == 5) {
            echo 'I am out of here, $count is ' . $count . '<br>';
            break;
        }
        echo "hello student_".$count." ".$y."_".$x,'<br>';
        $count++;
    }
}
echo 'First call<br>';
hello();
echo 'Second call<br>';
hello();
echo 'Third call<br>';
hello();

RESULTS

First call<br>
hello student_ Level_2<br>
hello student_1 Level_2<br>
hello student_2 Level_2<br>
hello student_3 Level_2<br>
hello student_4 Level_2<br>
I am out of here, $count is 5<br>
Second call<br>
I am out of here, $count is 5<br>
Third call<br>
I am out of here, $count is 5<br>

A Static variable is only initialised the first time it is seen, the first call of the function in this case.

Upvotes: 4

Related Questions