为后代键入提示 类

Type hint for descendant classes

来自文档页面 http://php.net/manual/en/language.oop5.typehinting.php

如果 class 或接口被指定为类型提示,则其所有子项或实现也被允许。

但是:

class PimpleChild extends Pimple {
//...
}
interface Pimple_Config {
    public function configure(Pimple $container);
}
class PimpleConfigurer_Factories implements Pimple_Config {
    public function configure(PimpleChild $container) {
    //...
    }
}

returns 致命错误。为什么?

来自同一个typehinting section you linked to:

The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

要使方法签名相同,它们必须包含完全相同的类型提示。而且也很相关,因为它很相似...

来自手册的 OOP Basics - extends 部分:

When overriding methods, the parameter signature should remain the same or PHP will generate an E_STRICT level error. This does not apply to the constructor, which allows overriding with different parameters.

如果我没记错的话你会得到这个错误:

Declaration of PimpleConfigurer_Factories::configure() must be compatible with Pimple_Config::configure(Pimple $container) ...

这意味着:如果你在超级class或接口中定义一个方法,所有子classes(或实现接口的classes)必须完全使用这个定义。您不能在此处使用其他类型。

至于你引用的文档:

If class or interface is specified as type hint then all its children or implementations are allowed too.

这仅意味着您可以传递特定类型或其所有子类型的变量。

例如:假设您有以下 classes:

class Car {
    protected $hp = 50;
    public function getHp() { return $this->hp; }
}

class SuperCar extends Car {
    protected $hp = 700;
}

以及类型提示的函数(或方法,没有区别):

function showHorsePower(Car $car) {
    echo $car->getHp();
}

您现在可以将 Car 类型的所有对象及其所有子 classes(此处为 SuperCar)传递给此函数,例如:

showHorsePower(new Car());
showHorsePower(new SuperCar());