Skip to content

StaticInvocationViaThis ​

warning on by default quick-fix

Group: Code style · PhpStorm name: StaticInvocationViaThisInspection

Calling a static method through an object ($this->make() or $obj->make()) hides the fact that no instance is involved. Use self::/ClassName:: so the call reads as what it is.

Example ​

php
<?php
class Palette {
    public static function shade($level) { return $level; }
    public static function staticTone() { return 0; }
    public function tint() { return 1; }

    public static function fromStatic() {
        return self::shade(1);
    }

    public function render() {
        $a = $this->shade(2);
        $b = $this->tint();
        $c = $this->staticTone();
        $d = self::shade(3);
        $e = function () { return $this->shade(4); };
    }
}

function paint(Palette $given) {
    $local = new Palette();
    $x = $local->shade(5);
    $y = (new Palette())->shade(6);
    $z = $given->shade(7);
    $w = makePalette()->shade(8);
    return function () use ($local) { return $local->shade(9); };
}

Reported:

  • line 12: Static method shade() called through $this; use self::shade().
  • line 22: Static method shade() called on an instance; call it with ::.
  • line 23: Static method shade() called on an instance; call it with ::.

Options ​

OptionTypeDefaultEffect
EXCEPT_PHPUNIT_ASSERTIONSbooltrueSkip static methods declared in PHPUnit framework classes and Symfony's test assertion traits (E3).
EXCEPT_ELOQUENT_MODELSbooltrueSkip static methods declared in Laravel's Eloquent base model (E4).

Configure ​

In custos.json:

json
{
  "rules": {
    "StaticInvocationViaThis": {
      "enabled": false,
      "options": {
        "EXCEPT_PHPUNIT_ASSERTIONS": true,
        "EXCEPT_ELOQUENT_MODELS": true
      }
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore StaticInvocationViaThis

/**
 * @noinspection StaticInvocationViaThisInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.