Skip to content

Commit 398df87

Browse files
phpstan-botclaude
andcommitted
Also detect static $this as fatal error
Add ThisInStaticStatementRule to report "Cannot use $this as static variable." alongside the existing global $this and catch $this checks. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent e210bca commit 398df87

3 files changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Variables;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Analyser\Scope;
7+
use PHPStan\DependencyInjection\RegisteredRule;
8+
use PHPStan\Rules\Rule;
9+
use PHPStan\Rules\RuleErrorBuilder;
10+
use function is_string;
11+
12+
/**
13+
* @implements Rule<Node\Stmt\Static_>
14+
*/
15+
#[RegisteredRule(level: 0)]
16+
final class ThisInStaticStatementRule implements Rule
17+
{
18+
19+
public function getNodeType(): string
20+
{
21+
return Node\Stmt\Static_::class;
22+
}
23+
24+
public function processNode(Node $node, Scope $scope): array
25+
{
26+
$errors = [];
27+
foreach ($node->vars as $var) {
28+
if (!is_string($var->var->name)) {
29+
continue;
30+
}
31+
if ($var->var->name !== 'this') {
32+
continue;
33+
}
34+
35+
$errors[] = RuleErrorBuilder::message('Cannot use $this as static variable.')
36+
->identifier('static.this')
37+
->nonIgnorable()
38+
->build();
39+
}
40+
41+
return $errors;
42+
}
43+
44+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Variables;
4+
5+
use PHPStan\Rules\Rule;
6+
use PHPStan\Testing\RuleTestCase;
7+
8+
/**
9+
* @extends RuleTestCase<ThisInStaticStatementRule>
10+
*/
11+
class ThisInStaticStatementRuleTest extends RuleTestCase
12+
{
13+
14+
protected function getRule(): Rule
15+
{
16+
return new ThisInStaticStatementRule();
17+
}
18+
19+
public function testBug14351(): void
20+
{
21+
$this->analyse([__DIR__ . '/data/bug-14351.php'], [
22+
[
23+
'Cannot use $this as static variable.',
24+
19,
25+
],
26+
]);
27+
}
28+
29+
}

tests/PHPStan/Rules/Variables/data/bug-14351.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,7 @@ function foo(): void {
1414
function foo(): void {
1515
global $this; // should report: Cannot use $this as global variable
1616
}
17+
18+
function bar(): void {
19+
static $this; // should report: Cannot use $this as static variable
20+
}

0 commit comments

Comments
 (0)