1.2.575. Inherited Static Variable

Static variables are distinct when used in an inherited static method. In PHP 8.1, the static variable will also be inherited, and shared between the two methods, like a static property.

<?php

// Code extracted from the RFC
class A {
    public static function counter() {
        static $i = 0;
        return ++$i;
    }
}
class B extends A {}

var_dump(A::counter()); // int(1)
var_dump(A::counter()); // int(2)
var_dump(B::counter()); // int(1)
var_dump(B::counter()); // int(2)

?>

See also PHP RFC: Static variables in inherited methods.

1.2.575.1. Suggestions

  • Define the method in the child class to enforce the distinct behavior

  • Replace the static variable by a static property to make this PHP 8.1 ready

1.2.575.2. Specs

Short name

Variables/InheritedStaticVariable

Rulesets

All, Changed Behavior, CompatibilityPHP81

Exakat since

2.2.2

PHP Version

With PHP 8.0 and older

Severity

Minor

Time To Fix

Quick (30 mins)

Changed Behavior

PHP 8.1 - More

Precision

Medium

Features

static-variable, inheritance

Available in

Entreprise Edition, Exakat Cloud