PHP7.2环境下PHPStan报__toString返回值不匹配的问题如何解决
__toString() should return string but returns string|false in PHP 7.2 Since you're stuck on PHP 7.2 (where throwing exceptions from __toString() isn't allowed), let's work through a couple of solid solutions that satisfy both PHP's runtime requirements and PHPStan's static analysis checks.
The Core Problem
json_encode() can return false if it fails to encode your $payload (e.g., invalid UTF-8 characters, recursive object references). Since __toString() is required to return a string, PHPStan flags this mismatch—and you can't rely on exceptions to handle the failure in PHP 7.2.
Solution 1: Handle Failure with a Fallback String
Instead of throwing an exception, return a valid string that represents the failure state. This could be a JSON-formatted error message or a simple descriptive string:
public function __toString(): string { $json = json_encode($this->payload); // If encoding fails, return a valid fallback string if ($json === false) { // Option 1: JSON-formatted error return '{"error": "Failed to encode payload"}'; // Option 2: Simple human-readable message // return '[Payload could not be converted to JSON]'; } return $json; }
This guarantees that __toString() always returns a string, so PHPStan will stop complaining, and your PHP 7.2 runtime won't throw an error.
Solution 2: Ensure $payload is Always Encodable (Prevent Failure Upfront)
If you can control the data in $payload, add validation earlier in your code to ensure it can be safely encoded to JSON. For example:
- Check for invalid UTF-8 characters and sanitize them
- Avoid recursive object references
- Ensure all data types are JSON-serializable
This way, json_encode() will never return false, and you can keep your original __toString() implementation—though it's still good practice to add a fallback just in case.
Why Your Original Fix Didn't Work
PHP 7.4 introduced support for throwing exceptions from __toString(), but this feature isn't available in 7.2. Your runtime error is a direct result of that version limitation, so we have to use string-based fallbacks instead.
内容的提问来源于stack exchange,提问作者Ivan MIhael Čergar

