当继承的接口用于类型提示时,为什么 PHP 会发出兼容性错误?

Why does PHP emit compatibility error when inherited interfaces are used for type hinting?

请仔细查看以下两个代码块。产生的 ErrorWarning 放在相应的代码块下面。

我觉得有趣!我认为两者应该以相同的方式行事,并且它们不应该发出任何错误或警告,因为它们在我看来在逻辑上是有效的。

这是 PHP 错误,还是我遗漏了什么?

顺便说一句,我相信问题和代码非常简单且不言自明,所以我不打算进一步解释。 :-)

interface A {}

interface B extends A {}

class X implements A {
    public function test() : A {}
}

class Y extends X implements B {
    public function test() : B {}
}

致命错误:Y::test() 的声明:B 必须与 X::test() 兼容:A

interface A {}

interface B extends A {}

class X implements A {
    public function test( A $a ) {}
}

class Y extends X implements B {
    public function test( B $b ) {}
}

警告:Y::test(B $b) 的声明应与 X::test(A $a

兼容

我想我自己找到了答案。

由于继承的接口可以有额外的声明(继承的类型可以有额外的属性),它们在逻辑上是完全不同的,因此 PHP 发出的错误/警告是绝对正确的。

感谢您阅读问题和答案。希望这会帮助其他人更好地理解接口作为类型的使用。

好消息!第一部分将从 PHP 7.4 开始工作。 :-)