Error Identifier: classConstant.dynamicFetch
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 = 'bar';
}
$name = 'BAR';
echo Foo::{$name};
Why is it reported? #
Fetching class constants with a dynamic name (using a variable expression) is a feature only available in PHP 8.3 and later. If the project targets an earlier PHP version, this syntax is not supported and will cause a syntax error.
How to fix it #
If upgrading to PHP 8.3 or later is an option, update the PHP version in the PHPStan configuration.
Otherwise, use the constant() function to access the class constant dynamically:
<?php declare(strict_types = 1);
$name = 'BAR';
-echo Foo::{$name};
+echo constant(Foo::class . '::' . $name);
Non-ignorable error #
This error cannot be ignored using @phpstan-ignore or the ignoreErrors configuration. Non-ignorable errors indicate code that would cause a crash or a fatal error at runtime, or a fundamental problem in the analysed code that must be addressed.
Rules that report this error #
- PHPStan\Rules\Constants\DynamicClassConstantFetchRule [1]