Skip to content

Method static variables cannot be changed via reflection #9177

@mvorisek

Description

@mvorisek

Description

The following code:

<?php

class A
{
    public function test()
    {
        static $v = [];
        $v[] = 'x';
    }
}

$r = new \ReflectionMethod(A::class, 'test');
print_r($r->getStaticVariables());

$a = new A();
$a->test();
print_r($r->getStaticVariables());
$a->test();
print_r($r->getStaticVariables());

$r->getStaticVariables()['v'][0] = ['replace_first_x'];
print_r($r->getStaticVariables());

$a->test();
print_r($r->getStaticVariables());

demo: https://3v4l.org/e67fY

Resulted in this output:

...
    [v] => Array
        (
            [0] => x
            [1] => x
            [2] => x
        )
)

But I expected this output instead:

...
    [v] => Array
        (
            [0] => replace_first_x
            [1] => x
            [2] => x
        )
)

The usecase might look absurd, but I have 3rd party lib which stores some objects in static variable which are never released and causes php memory to grow infinitely.

Is there any workaround to my problem (ie. how clear/modify method's static variable from outside the method)?

Also, can this be considerer a bug? I would expect the variable to be returned by a reference, so it can be modified via reflection.

PHP Version

any

Operating System

any

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions