界面中的类型提示

Ter*_*ony 4 php oop interface

为什么类type-hint与接口必须100%相同?
我的意思是,为什么它不能接受实现类作为类型提示?

说清楚一点

<?php
interface MyInterface
{
    public function doMethod(SomeInterface $a)
    {
    }
}

class MyClass implements MyInterface
{
    public function doMethod(ClassThatImplementsSomeInterface $a)
     {
     }
}
Run Code Online (Sandbox Code Playgroud)

错误: Fatal error: Declaration of MyClass::doMethod() must be compatible with that of MyInterface::doMethod()

由于类类型提示实现了SomeInterface,我希望它不会破坏合同。
我为什么要它?由于界面灵活性的优势。
抽象类也是如此。
如果我重写代码,使方法“ do”没有类型提示,那么我知道它将“修复”它。
但是,我认为我应该以某种方式定义$a必须执行的类型提示的合同SomeInterface
而且,为什么我不只使用相同的type-hint SomeInterface
那是因为SomeInterface我不需要某些方法。
那么,此限制的意义何在?

可再现的键盘:http : //codepad.org/2PLd8AmV

Dan*_* W. 5

答案很简单,您需要能够依赖接口所需的对象。

真实的例子:

接口要求APPLE

现在,您尝试实现一个说I require a GREEN APPLE(仍然是一个苹果!)的类。

现在有人尝试实现您的接口并将其放入绿色苹果类中。他尝试放入RED APPLE与兼容APPLE但不兼容的GREEN APPLE

=>砰,合同坏了!

编码示例:

interface MyInterface
{
    public function doMethod(SomeInterface $a);
}

class MyClass implements MyInterface
{
    public function doMethod(ClassThatImplementsSomeInterface $a) { }
}

class DifferentClass implements SomeInterface { }

$ding = new MyClass();
$ding->doMethod(new DifferentClass);
Run Code Online (Sandbox Code Playgroud)

这是行不通的,因为DifferentClass不是ClassThatImplementsSomeInterface