Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-Initializing static members in PHP

Tags:

php

static

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?

like image 889
Sharpzain120 Avatar asked Aug 17 '26 02:08

Sharpzain120


1 Answers

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.

like image 76
Linus Kleen Avatar answered Aug 18 '26 15:08

Linus Kleen