Search code examples
phpmagic-methodsphp-8

Fatal error: Declaration of Foo::__toString(): void must be compatible with Stringable::__toString(): string


After upgrading to PHP 8 I'm now seeing this Fatal error what's wrong with my code ? And what is this Stringable?


Solution

  • Prior to PHP 8 it was possible for a programmer to write magic methods that have signatures that don't match the internal signature of them.

    So for example

    class Foo {
        public function __toString(): void {
        
        }
    }
    

    Although the return type void doesn't match the method's documentation

    public __toString ( void ) : string
    

    PHP was not complaining!

    However, with the advent of PHP 8 the signature of a magic method must follow that magic method's documentation.

    public function __toString(): string {
    
    }
    

    Otherwise you'll see a Fatal error!

    Note: The __construct() and __destruct() are excluded from this new change, since there is not concept of them returning values in almost every computer language.


    What is this Stringable?

    Stringable is an interface that is added automatically to classes that implement the __toString() method

    See the RFC for more information.