Error Identifier: varTag.noVariable
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 doFoo(array $list): void
{
/** @var int */
foreach ($list as $key => $val) {
// ambiguous: which variable does @var apply to?
}
}
Why is it reported? #
The @var PHPDoc tag does not specify a variable name, and the context has multiple variables that it could apply to. When there is ambiguity about which variable the @var tag refers to, PHPStan requires the variable name to be specified explicitly.
This is reported in the following situations:
- A
@vartag without a variable name above aforeachloop with multiple variables (key and value). - A
@vartag without a variable name above astaticdeclaration with multiple variables. - A
@vartag without a variable name above aglobaldeclaration with multiple variables. - A
@vartag without a variable name above a statement that is not a variable assignment.
<?php declare(strict_types = 1);
function doBar(): void
{
/** @var int */
static $a, $b;
// ambiguous: does @var apply to $a or $b?
}
How to fix it #
Add the variable name to the @var tag:
<?php declare(strict_types = 1);
function doFoo(array $list): void
{
- /** @var int */
+ /** @var int $val */
foreach ($list as $key => $val) {
}
}
For multiple variables, use multiple @var tags with explicit names:
<?php declare(strict_types = 1);
function doBar(): void
{
- /** @var int */
- static $a, $b;
+ /**
+ * @var int $a
+ * @var string $b
+ */
+ static $a, $b;
}
How to ignore this error #
You can use the identifier varTag.noVariable to ignore this error using a comment:
// @phpstan-ignore varTag.noVariable
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: varTag.noVariable