Error Identifier: new.staticInAbstractClassStaticMethod
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);
abstract class Creator
{
public static function create(): static
{
return new static();
}
}
Why is it reported? #
Using new static() inside a static method of an abstract class is unsafe because the static method can be called directly on the abstract class itself, e.g. Creator::create(). Since abstract classes cannot be instantiated, this would result in a fatal error at runtime.
Unlike instance methods which require an already-instantiated object, static methods can be called without an instance, making AbstractClass::staticMethod() a valid call site that would crash.
How to fix it #
Make the static method abstract so that each concrete subclass must provide its own implementation:
<?php declare(strict_types = 1);
abstract class Creator
{
- public static function create(): static
- {
- return new static();
- }
+ abstract public static function create(): static;
}
Alternatively, make the class final so it can be safely instantiated:
<?php declare(strict_types = 1);
-abstract class Creator
+final class Creator
{
public static function create(): static
{
return new static();
}
}
How to ignore this error #
You can use the identifier new.staticInAbstractClassStaticMethod to ignore this error using a comment:
// @phpstan-ignore new.staticInAbstractClassStaticMethod
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: new.staticInAbstractClassStaticMethod
Rules that report this error #
- PHPStan\Rules\Classes\NewStaticInAbstractClassStaticMethodRule [1]