%s::__toString() must return a string

Description

The magic method __toString converts the current object into a string. Hence, and even if the return type of that method is not explicitly set, it MUST return a string.

With strict types, it may only be a string. Without them, integers and booleans are auto cast silently.

Adding the return type or not does not change this behavior. It is actually set, and could not be any other type anyway.

Example

<?php

class X {
    function __toString() {
        return 1;
    }
}

(string) (new X);

?>

Literal Examples

  • X::__toString() must return a string

Solutions

  • Return a string.

  • Cast the value to a string before returning.