Search code examples
phpstatic

PHP static var in function shared between child class objects


I'm surprised that when using a static variable inside a function for simple caching, that the static value is retained between different child classes of the class the function lives in.

Has this changed between PHP8.0 and 8.1?

Code to reproduce

class top{

    public function cacheValue(){
        static $cache;
        if (!isset($cache)) {
            $cache=get_class($this)."\n";
        }
        return $cache;
    }
}

class child1 extends top{

}
class child2 extends top{

}


$a = new child1;

$b = new child2;

echo $a->cacheValue();
echo $b->cacheValue();

Expected result:

child1 child2

Actual result:

child1 child1


Solution

  • Yes, this changed in PHP 8.1. From the Migration Guide:

    Usage of static Variables in Inherited Methods
    When a method using static variables is inherited (but not overridden), the inherited method will now share static variables with the parent method.
    ...
    This means that static variables in methods now behave the same way as static properties.