Method Could Be Static
ID |
php.method_could_be_static |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Php |
Tags |
best-practice, code_smell |
Description
Reports an instance method whose body never touches the object context — it references
neither the $this pseudo-variable nor a parent:: member — and could therefore be
declared static.
Rationale
A method that never reads or writes instance state is a pure helper that happens to live on
the class. Declaring it static documents that intent: callers see it does not depend on a
particular object, the engine need not bind $this, and the method can be reused without
constructing an instance. Leaving such a method non-static is a mild code smell that hides
the routine’s true nature and invites needless object creation.
Magic methods (construct, get, __toString, …) are invoked by the runtime on an
instance and are never reported; abstract and interface methods have no body to analyse and
exist to be overridden, so they are skipped too. A $this used inside a closure declared in
the method counts as using the instance, because such a closure binds the enclosing $this.
<?php
abstract class Calculator
{
private int $base;
public function add(int $a, int $b): int // FLAW — no $this / parent::, could be static
{
return $a + $b;
}
public function withBase(int $a): int // OK — reads $this->base
{
return $this->base + $a;
}
public function withParent(): int // OK — calls parent::
{
return parent::compute();
}
public static function already(int $a): int // OK — already static
{
return $a * 2;
}
}
Remediation
If the method genuinely does not need an instance, add the static keyword and call it via
ClassName::method() (or self::method() / static::method() from inside the class). If a
dependency on instance state was intended but accidentally omitted, add the missing
$this→ reference instead.