1.2.836. No Static Variable In A Method

Refactor static variables into properties.

Inside a class, it is recommended to use the class properties, static or not, to hold values between calls to the method. Inside a function, or a closure <https://www.php.net/`closure>`_, no such container is available, so static variables may be useful. Although, a refactoring to a class is also recommended here.

Properties have clear definitions, and are less surprising than static variables. The static variable is easier to refactor as a static property. It is also possible to refactor it as a property, although it may impact the behavior of the previous code, or require extra work.

<?php

class barbar {
    function foo() {
        static $counter = 0;

        // count the number of calls of this method
        return ++$counter;
    }
}

class bar {
    static $counter = 0;

    function foo() {
        // count the number of calls of this method
        return ++self::$counter;
    }
}

?>

1.2.836.1. Suggestions

  • Refactor the variable into a static property

  • Refactor the variable into a property and then use dependency injection

1.2.836.2. Specs

Short name

Variables/NoStaticVarInMethod

Rulesets

All, Class Review, Suggestions

Exakat since

2.2.1

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

static-variable

Available in

Entreprise Edition, Exakat Cloud