PHP - 接口继承 - 声明必须兼容 [英] PHP - Interface inheritance - declaration must be compatible
本文介绍了PHP - 接口继承 - 声明必须兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有界面:
interface AbstractMapper
{
public function objectToArray(ActiveRecordBase $object);
}
和班级:
class ActiveRecordBase
{
...
}
class Product extends ActiveRecordBase
{
...
}
========
但我不能这样做:
interface ExactMapper implements AbstractMapper
{
public function objectToArray(Product $object);
}
或者这个:
interface ExactMapper extends AbstractMapper
{
public function objectToArray(Product $object);
}
我收到错误声明必须兼容
那么,有没有办法在PHP中执行此操作?
So, is there a way to do this in PHP?
推荐答案
不,必须实现完全的接口。如果将实现限制为更具体的子类,则它不是相同的接口/签名。 PHP没有泛型或类似机制。
No, an interface must be implemented exactly. If you restrict the implementation to a more specific subclass, it's not the same interface/signature. PHP doesn't have generics or similar mechanisms.
您总是可以手动签入代码,当然:
You can always manually check in code, of course:
if (!($object instanceof Product)) {
throw new InvalidArgumentException;
}
这篇关于PHP - 接口继承 - 声明必须兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文