Search code examples
phpstatic-variables

static memory in functions [PHP]


I have research function with static variable, lets look the next code:

(Warning! For test you must have enabled xdebug in php.ini)

function a()
{
    static $var = 10;
    xdebug_debug_zval('var');
    return $var;
}
a();

It's output the next: var:(refcount=2, is_ref=1),int 10

What's going on? Why is refcount=2? Where second reference?

P.S So if we have var:(refcount=2, is_ref=1),int 10. It's means why we can't save reference in static variable.

For the user Mark Baker

function a()
{
    $var = 10;
    xdebug_debug_zval('var');
    return $var;
}
a();

Outputs: var:(refcount=1, is_ref=0),int 10

Info: Calling a function does not use the variable argument that no problems with outputting information. Therefore, in view of arguments used by name of the variable written into a string


Solution

  • Access to static variables in PHP creates a reference to an internal array of statics upon usage.

    You can verify this by noticing that it is impossible to store references in static variables:

    function a() {
        static $var = 1;
        var_dump($var);
        $var = &$ref;
        $var = 2;
    }
    a(); a();
    // prints int(1) int(1)