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);
function doFoo(int $int): void
{
new $int;
}
Why is it reported? #
The dynamic instantiation syntax new $expr requires $expr to be either a string holding a class name or an object whose class should be instantiated. When $expr is any other type — such as int, float, bool, array, or a union that includes those types — PHP throws a fatal Error at runtime:
Uncaught Error: Class name must be a valid object or a string
A nullable string (string|null) is also reported, because passing null triggers the same fatal error.
How to fix it #
Make sure the expression used after new resolves to a class name or an object. Narrow the type so the non-object cases are excluded:
-function doFoo(int $int): void
+function doFoo(string $class): void
{
- new $int;
+ new $class;
}
When the value can legitimately hold several types, narrow the type before instantiating:
/** @param int|string $intOrString */
function doFoo($intOrString): void
{
+ if (!is_string($intOrString)) {
+ return;
+ }
new $intOrString;
}
For a parameter that is meant to receive a class name, use the class-string type so PHPStan and other developers know only class names are accepted:
-/** @param string $class */
+/** @param class-string $class */
function doFoo(string $class): void
{
new $class;
}
How to ignore this error #
You can use the identifier new.nonObject to ignore this error using a comment:
// @phpstan-ignore new.nonObject
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.nonObject
Rules that report this error #
- PHPStan\Rules\Classes\InstantiationRule [1]