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?

1
  • 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. Commented Feb 28, 2020 at 16:05

1 Answer 1

3

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) ?: '';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.