Error Identifier: staticClassAccess.privateConstant
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
{
private const FOO = 1;
public function doFoo(): int
{
return static::FOO;
}
}
Why is it reported? #
Accessing a private constant through static:: is unsafe in a non-final class. The static keyword uses late static binding, which resolves to the actual class at runtime. If a child class extends Foo, static::FOO in the child’s context would try to access Foo::FOO, but private constants are not visible to child classes. This leads to a fatal error at runtime.
How to fix it #
Use self:: instead of static:: to access private constants, since they cannot be overridden in child classes:
<?php declare(strict_types = 1);
class Foo
{
private const FOO = 1;
public function doFoo(): int
{
- return static::FOO;
+ return self::FOO;
}
}
Alternatively, make the class final if it is not intended to be extended:
<?php declare(strict_types = 1);
-class Foo
+final class Foo
{
private const FOO = 1;
public function doFoo(): int
{
return static::FOO;
}
}
How to ignore this error #
You can use the identifier staticClassAccess.privateConstant to ignore this error using a comment:
// @phpstan-ignore staticClassAccess.privateConstant
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: staticClassAccess.privateConstant
Rules that report this error #
- PHPStan\Rules\Classes\AccessPrivateConstantThroughStaticRule [1]