PHPJungle
PHPJungle

Reputation: 522

Re-declaration of the same static variable inside a function

I have such a function, 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 the outputs would be: 2 11, but the outputs was: 11 12. Why?

Upvotes: 3

Views: 1539

Answers (3)

stack_d_code
stack_d_code

Reputation: 1256

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

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

Upvotes: 0

sandeep soni
sandeep soni

Reputation: 303

Static works the same way as it does in a class. The variable is shared across all instances of a function. so if you initialize same static variable many time then it will always take latest value.

Upvotes: 0

someOne
someOne

Reputation: 1675

If you declare and initialize the same static variable more than once inside a function, then the variable will take the value of the last declaration (static declarations are resolved in compile-time.)

In this case, the static variable of $a will take the value of 10 in the compile time, ignoring the value of 1 in the previous same declaration.

Upvotes: 2

Related Questions