Re-declaring the same static variable inside a function

I have a function like this and I declare the same static variable twice with different values . Then I called the function, but the result surprised me.

function question(){
    static $a=1;
    $a++;
    echo $a; // output:?
    static $a=10;
    $a++;
    echo $a; // output:?
}

      

I thought that the outputs will be: 2 11

but yields were: 11 12

. Why?

+3


source to share


3 answers


If you declare and initialize the same static variable more than once within a function, then the variable takes on the value of the last declaration (static declarations are resolved at compile time).



In this case, the static variable $a

will take on a value 10

at compile time, ignoring the value 1

in the previous declaration.

+2


source


Static works the same way as in a class. The variable is common to all instances of the function. so if you initialize the same static variable many times, then it will always have the last value.



0


source


A static variable exists only in the declared scope of local functions, but it does not lose its value when program execution leaves this scope. The use of the Static keyword by itself is such that it will not lose the current count. So, in your case, the function stops at $ a = 10; $ A ++; Hence, you have 11 and 12 as output. If you want the result to be 2 and 11; save only one declaration as shown below.

function question(){
    $a=1;
    $a++;
    echo $a; // output:?
    static $a=10;
    $a++;
    echo $a; // output:?
}

      

0


source







All Articles