Error Identifier: class.toStringDeprecated
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
{
/**
* @deprecated
*/
public function __toString(): string
{
return 'foo';
}
}
function doFoo(Foo $foo): string
{
return (string) $foo;
}
Why is it reported? #
The __toString() method on the class is marked as @deprecated. Casting an instance of this class to a string (via (string), string interpolation, echo, or any implicit string conversion) invokes the deprecated method. This rule is part of the phpstan-deprecation-rules package and warns about usages of deprecated string conversions so they can be replaced before the method is removed.
How to fix it #
Use an explicit method to get the string representation instead of relying on the deprecated __toString():
<?php declare(strict_types = 1);
function doFoo(Foo $foo): string
{
- return (string) $foo;
+ return $foo->getName();
}
How to ignore this error #
You can use the identifier class.toStringDeprecated to ignore this error using a comment:
// @phpstan-ignore class.toStringDeprecated
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: class.toStringDeprecated