My function is __toString
:
public function __toString(): string
{
return json_encode($this->payload);
}
This is the error that I receive from PhpStan, blocking me from making a commit:
Method App\DTO\GenericMessageDTO::__toString() should return string but returns string|false.
I tried with exception but is not compatible with my php 7.2 it says Throwing an exception from ''__toString'' is only possible since PHP 7.4
public function __toString(): string
{
if ($this->payload === false) {
throw new \Exception("No payload");
}
return json_encode($this->payload);
}
How can I fix this?
You are returning from json_encode
directly, and this legacy function has a return type of string|false
, as described here. If for any reason it fails to encode $payload
, it will return false
instead of a string.
And as you discovered, throwing an exception in __toString()
is not accepted unless you upgrade to 7.4 (the sooner the better! :))
This would be a simple way to fix your toString()
declaration, to make sure you always return a string.
public function __toString(): string
{
return json_encode($this->payload) ?: '';
}