Error Identifier: method.nonObject
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|string $value): void
{
$value->toString(); // ERROR: Cannot call method toString() on int|string.
}
Why is it reported? #
A method is being called on a value whose type does not support method calls. Methods can only be called on objects. In the example above, $value is int|string, neither of which is an object type, so calling a method on it is invalid.
How to fix it #
Narrow the type to an object before calling the method:
<?php declare(strict_types = 1);
-function doFoo(int|string $value): void
+function doFoo(int|string|Stringable $value): void
{
- $value->toString();
+ if ($value instanceof Stringable) {
+ $value->toString();
+ }
}
Or change the parameter type to accept only objects that have the desired method:
<?php declare(strict_types = 1);
-function doFoo(int|string $value): void
+function doFoo(Stringable $value): void
{
$value->toString();
}
How to ignore this error #
You can use the identifier method.nonObject to ignore this error using a comment:
// @phpstan-ignore method.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: method.nonObject