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

1.2k views Asked by At

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

2

There are 2 answers

0
Rain On BEST ANSWER

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.

0
JSowa On

You must refactor your function __toString() from:

public function __toString(): void {
  //definition
}

to function returning string value.

public function __toString(): string {
  //definition
  return 'some string';
}