Sharpzain120
Sharpzain120

Reputation: 375

Re-Initializing static members in PHP

I have a question in my todays Exam in which I have to determine the output.

<?php
function statfun($x)
{
    static $count=0;

    $count += $x;

    if ($count < 20) {
        echo "$count <br>";
        statfun(++$x);
    } else {
        echo "last num is $count";
    }
}

statfun(2);
?>

The output is

2
5
9
14
last num is 20

I dont know why this is the output. I know it is due to the static member but each time it comes into the function the member $count is re-initialized.I had saw the documentation at Static Keyword.

But there is nothing written regarding the re-initialization of static variable? Can we re-initialize the static variable in PHP? With the same or any other value?

Upvotes: 3

Views: 209

Answers (2)

Senad Meškin
Senad Meškin

Reputation: 13756

when you pass 2 count is set to 2 with $count+=$x; then you have called statfun(++$x) which is $x+1 and that is 2+1=3 so now $count will be $count+3 and that is 5, and then you call statfun with the value of 3 then $count will $count+(3+1) = 9 and so on and so on

static variable will hold its state. So if you call it like this

So basically static variable will hold its value and will not be re-initialized.

Upvotes: 3

Linus Kleen
Linus Kleen

Reputation: 34632

each time it comes into the function the member $count is re-initialized

This is incorrect. Static variables are initialized only once which is how statically declared variables differ from "ordinary" variables. So basically, you're assigning an initial value to $count. In multiple calls to statfun(), this static variable's value is preserved and can be reused.

From the manual, section "Using static variables":

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

Also look at the example-code in the manual. The difference stated there should answer your question.

Upvotes: 5

Related Questions