Error Identifier: cast.string
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);
$value = (string) new stdClass();
Why is it reported? #
The expression being cast to string is of a type that cannot be converted to a string. PHP does not support casting certain types to string unless the class implements the __toString() method. Attempting to cast an object without __toString() to string will result in a fatal error at runtime.
In the example above, stdClass does not implement __toString(), so it cannot be cast to string.
How to fix it #
Implement the __toString() method on the class:
<?php declare(strict_types = 1);
-$value = (string) new stdClass();
+class MyClass
+{
+ public function __toString(): string
+ {
+ return 'my value';
+ }
+}
+
+$value = (string) new MyClass();
Or extract the string value from the object explicitly:
<?php declare(strict_types = 1);
-$value = (string) new stdClass();
+$obj = new stdClass();
+$obj->name = 'hello';
+$value = $obj->name;
How to ignore this error #
You can use the identifier cast.string to ignore this error using a comment:
// @phpstan-ignore cast.string
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: cast.string
Rules that report this error #
- PHPStan\Rules\Cast\InvalidCastRule [1]