后代类的类型提示


Type hint for descendant classes

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

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

但:

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

返回致命错误。为什么?

如果我

没记错的话,你会得到这个错误:

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

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

至于您从文档中引用的:

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

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

例如:假设您有以下类:

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 类型的所有对象及其所有子类(此处为 SuperCar)传递给此函数,例如:

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

来自您链接到的同一类型提示部分:

实现接口的类必须使用与接口中定义的完全相同的方法签名。不这样做将导致致命错误。

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

从手册的 OOP 基础知识 - extends 部分:

重写方法时,参数签名应保持不变,否则 PHP 将生成E_STRICT级错误。这不适用于构造函数,它允许使用不同的参数进行重写。