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

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

升级到 PHP 8 后,我现在看到了 Fatal error 我的代码有什么问题?这是什么Stringable

在 PHP8 之前,程序员可以编写签名与内部签名不匹配的魔术方法。

例如

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

尽管 return 类型 void 与方法的 documentation

不匹配
public __toString ( void ) : string

PHP没有抱怨!

但是,随着 PHP8 的出现,魔术方法的签名必须遵循该魔术方法的文档。

public function __toString(): string {

}

否则你会看到 Fatal error!

注意: __construct()__destruct() 被排除在这个新变化之外,因为它们没有 returning 值的概念几乎所有计算机语言。


这是什么字符串?

Stringable 是自动添加到 类 的接口,实现了 __toString() 方法

有关详细信息,请参阅 RFC

您必须重构您的函数 __toString() 来自:

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

函数返回 string 值。

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