Fix phpstan/phpstan#14349: Missing "Fatal error: Cannot re-assign $this"#5276
Conversation
… variable - Added new InvalidForeachVariableRule that detects $this used as foreach value or key variable - Rule is registered at level 0 since this is a fatal error in PHP - New regression test in tests/PHPStan/Rules/Variables/data/bug-14349.php
ondrejmirtes
left a comment
There was a problem hiding this comment.
Create a rule for VariableAssignNode. Extract the part about assigning $this from InvalidAssignVarRule there. And also make sure the same rule for VariableAssignNode also covers this foreach scenario.
Create InvalidVariableAssignRule for VariableAssignNode that detects $this reassignment in all contexts (regular assignments, foreach variables, list destructuring). Extract the $this check from InvalidAssignVarRule into this new unified rule. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
All done. Here's a summary of the changes:
All 11,634 tests pass and |
ondrejmirtes
left a comment
There was a problem hiding this comment.
Add bug-3585.php to the test of the new rule
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
Already handled — the change has been committed and pushed. All tests and static analysis passed. |
ondrejmirtes
left a comment
There was a problem hiding this comment.
tests/PHPStan/Rules/Variables/data/bug-14349.php should be added to excluded files in make lint in Makefile
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
Done. Added |
Summary
PHP produces a fatal error "Cannot re-assign $this" when
$thisis used as a foreach value or key variable, but PHPStan did not report this. This PR adds a new rule to detect this error.Changes
src/Rules/Variables/InvalidForeachVariableRule.php— a new level 0 rule that checks foreach statements for$thisas value or key variabletests/PHPStan/Rules/Variables/InvalidForeachVariableRuleTest.php— test case for the new ruletests/PHPStan/Rules/Variables/data/bug-14349.php— test data covering$thisas value, by-ref value, and key in foreachRoot cause
There was no rule checking foreach variable names for
$this. The existingInvalidParameterNameRulecovered function/method parameters andInvalidLexicalVariablesInClosureUseRulecovered closureuse()clauses, but foreach was a gap.Test
The regression test verifies that
foreach ($a as $this),foreach ($a as &$this), andforeach ($a as $this => $v)all produce "Cannot re-assign $this." errors, whileforeach ($a as $ok)produces no error.Fixes phpstan/phpstan#14349