Error Identifier: for.variableOverwrite
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
function process(int $i): void
{
for ($i = 0; $i < 10; $i++) {
echo $i;
}
}
Why is it reported? #
This error is reported by phpstan/phpstan-strict-rules.
The initial assignment in a for loop overwrites a variable that already exists in the current scope. This means the previous value of the variable is lost, which is usually unintentional and can lead to bugs.
In the example above, the parameter $i is overwritten by the for loop initialization $i = 0, discarding the value that was passed to the function.
How to fix it #
Use a different variable name for the loop counter:
<?php declare(strict_types = 1);
function process(int $i): void
{
- for ($i = 0; $i < 10; $i++) {
- echo $i;
+ for ($j = 0; $j < 10; $j++) {
+ echo $j;
}
}
Or remove the conflicting variable from the outer scope if it is not needed:
<?php declare(strict_types = 1);
-function process(int $i): void
+function process(): void
{
for ($i = 0; $i < 10; $i++) {
echo $i;
}
}
How to ignore this error #
You can use the identifier for.variableOverwrite to ignore this error using a comment:
// @phpstan-ignore for.variableOverwrite
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: for.variableOverwrite
Rules that report this error #
- PHPStan\Rules\ForLoop\OverwriteVariablesWithForLoopInitRule [1] phpstan/phpstan-strict-rules