Error Identifier: new.noConstructor
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
{
}
new Foo(1, 2, 3); // ERROR: Class Foo does not have a constructor and must be instantiated without any parameters.
Why is it reported? #
A class that does not define a __construct() method is being instantiated with arguments. Since the class has no constructor, it does not accept any parameters during instantiation. Passing arguments to new for such a class is a runtime error in PHP.
How to fix it #
Remove the arguments from the instantiation:
<?php declare(strict_types = 1);
-new Foo(1, 2, 3);
+new Foo();
Or add a constructor to the class if the parameters are needed:
<?php declare(strict_types = 1);
class Foo
{
+ public function __construct(
+ private int $a,
+ private int $b,
+ private int $c,
+ ) {
+ }
}
new Foo(1, 2, 3);
How to ignore this error #
You can use the identifier new.noConstructor to ignore this error using a comment:
// @phpstan-ignore new.noConstructor
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.noConstructor
Rules that report this error #
- PHPStan\Rules\Classes\InstantiationRule [1]