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 $name): void
{
echo $$name;
}
Why is it reported? #
When using a variable variable with the $$name syntax, the $name expression must produce a string. PHP casts the name to string at runtime, so a string, an int, or an object implementing Stringable are all accepted. Values that cannot be cast to a string — such as an array or a plain object — are invalid and result in an error. In the example above, $name is an array, which cannot be used as a variable name.
This check is currently part of Bleeding Edge.
How to fix it #
Ensure the variable variable name can be cast to a string:
-function doFoo(array $name): void
+function doFoo(string $name): void
{
echo $$name;
}
Variable variables are hard to analyse and easy to misuse. When the set of names is known, an array is usually a clearer and safer alternative:
-function doFoo(string $name): void
+function doFoo(array $values, string $name): void
{
- echo $$name;
+ echo $values[$name];
}
How to ignore this error #
You can use the identifier variable.nameNotString to ignore this error using a comment:
// @phpstan-ignore variable.nameNotString
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: variable.nameNotString
Rules that report this error #
- PHPStan\Rules\Classes\ClassConstantRule [1]
- PHPStan\Rules\Methods\CallMethodsRule [1]
- PHPStan\Rules\Methods\CallStaticMethodsRule [1]
- PHPStan\Rules\Properties\AccessPropertiesInAssignRule [1]
- PHPStan\Rules\Properties\AccessPropertiesRule [1]
- PHPStan\Rules\Properties\AccessStaticPropertiesInAssignRule [1]
- PHPStan\Rules\Properties\AccessStaticPropertiesRule [1]
- PHPStan\Rules\Variables\DefinedVariableRule [1]