1.2.7. $this Is Not For Static Methods¶
Static methods shouldn’t use $this variable.
$this variable represents an object, the current object. It is not compatible with a static method, which may operate without any object.
While executing a static method, $this is actually set to NULL.
<?php
class foo {
static $staticProperty = 1;
// Static methods should use static properties
static public function count() {
return self::$staticProperty++;
}
// Static methods can't use $this
static public function bar() {
return $this->a; // No $this usage in a static method
}
}
?>
See also Static Keyword.
1.2.7.2. Connex PHP features¶
1.2.7.2.1. Suggestions¶
Remove the static keyword on the method, and update all calls to this method to use $this
Remove the usage of $this in the method, replacing it with static properties
Make $this an argument (and change its name) : then, make the method a function
1.2.7.2.2. Specs¶
Short name |
Classes/ThisIsNotForStatic |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
ClearPHP |
|
Available in |