Avoid This In Static
ID |
php.avoid_this_in_static |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Php |
Tags |
object-context, reliability |
Description
Reports a use of the $this pseudo-variable inside a method declared static (directly, or
within a closure declared in that static method). A static method has no object context, so
$this is unbound.
Rationale
$this refers to the current object instance. A static method is invoked on the class
itself, with no instance, so $this is undefined there; dereferencing it raises a fatal
Error: Using $this when not in object context. The same applies to a closure created
inside a static method: it has no instance to bind, plain or static. Catching this at
review time prevents a crash that only surfaces at runtime when the static method is actually
called.
<?php
class Registry
{
private string $name = 'default';
public static function create(): string
{
return $this->name; // FLAW — static method, $this is unbound
}
public static function build(): callable
{
return function () {
return $this->name; // FLAW — closure in a static method has no $this either
};
}
public function instance(): string
{
return $this->name; // OK — instance method, $this is valid
}
}
Remediation
If the member belongs to an instance, make the method non-static and call it on an object.
If the method is genuinely class-level, replace $this→member with the static form
(self::$property, static::method()) or pass the needed value in as a parameter.