Problem with phpStan error : __toString() should return string but returns string|false

Ivan MIhael Čergar :

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?

yivi :

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) ?: '';
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198557&siteId=1