Error Identifier: classConstant.nameType
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);
class Foo
{
public const BAR = 1;
}
function doFoo(int $name): void
{
echo Foo::{$name};
}
Why is it reported? #
PHP 8.3 introduced dynamic class constant fetching using the syntax ClassName::{$expr}. The expression used as the constant name must evaluate to a string. Passing a non-string value such as an int is not valid because class constant names are always strings.
How to fix it #
Ensure the expression used for the dynamic constant name is a string:
<?php declare(strict_types = 1);
-function doFoo(int $name): void
+function doFoo(string $name): void
{
echo Foo::{$name};
}
Or cast the value to a string:
<?php declare(strict_types = 1);
function doFoo(int $name): void
{
- echo Foo::{$name};
+ echo Foo::{(string) $name};
}
How to ignore this error #
You can use the identifier classConstant.nameType to ignore this error using a comment:
// @phpstan-ignore classConstant.nameType
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: classConstant.nameType
Rules that report this error #
- PHPStan\Rules\Constants\DynamicClassConstantFetchRule [1]