1

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?

Mike Doe
  • 16,349
  • 11
  • 65
  • 88
  • You can maybe return an empty string ? It is not ideal as you need to check yourself if something went wrong at each (implicit) call, but it seems there is no better solution. – Joffrey Schmitz Feb 28 '20 at 16:05

1 Answers1

2

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) ?: '';
}
yivi
  • 42,438
  • 18
  • 116
  • 138