参数类型可以在PHP中专用吗 [英] Can parameter types be specialized in PHP
问题描述
说我们有以下两个类:
abstract class Foo {
public abstract function run(TypeA $object);
}
class Bar extends Foo {
public function run(TypeB $object) {
// Some code here
}
}
TypeB类扩展了TypeA类.
The class TypeB extends the class TypeA.
尝试使用此方法会产生以下错误消息:
Trying to use this yields the following error message:
Bar :: run()的声明必须与Foo :: run()的声明兼容
在涉及参数类型时,PHP真的被打破了吗?还是我只是在这里遗漏了一点?
Is PHP really this broken when it comes to parameter types, or am I just missing the point here?
推荐答案
This answer is outdated since PHP 7.4 (partially since 7.2).
您描述的行为称为 协方差 并且在PHP中根本不支持.我不了解内部结构,但我可能会怀疑,在应用所谓的类型提示"检查时,PHP的核心根本不会评估继承树.
The behavior you describe is called covariance and is simply not supported in PHP. I don't know the internals but I might suspect that PHP's core does not evaluate the inheritance tree at all when applying the so called "type hint" checks.
顺便说一句,PHP也不支持 contravariance 上的这些类型提示(其他OOP语言通常支持的功能)-最有可能是上面提到的原因.因此,这也不起作用:
By the way, PHP also doesn't support contravariance on those type-hints (a feature commonly support in other OOP languages) - most likely to the reason is suspected above. So this doesn't work either:
abstract class Foo {
public abstract function run(TypeB $object);
}
class Bar extends Foo {
public function run(TypeA $object) {
// Some code here
}
}
最后是更多信息: 查看全文