来自文档页面 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/