php - 后代类的类型提示

标签 php type-hinting

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

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

但是:

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

返回 fatal error 。为什么?

最佳答案

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

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

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

至于您对文档的引用:

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

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

例如:假设您有以下类:

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());

关于php - 后代类的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28217727/

相关文章:

php - Tal条件,在同一行定义多个条件

javascript - AES - 加密 JS 和 PHP

php - PHP中的动态数组遍历

python - Pandas 的 Mypy/typeshed stub

python - 为包含 namedtuple 的列表键入提示

python - 代码 '_T = TypeVar(' _T')' 在 *.pyi 文件中是什么意思?

python - 如何对字典进行子类化,使其支持通用类型提示?

php - 为网络协作编码

PHP 数组没有返回值

python - 使用循环引用为注释类型创建别名时如何避免 NameError?