接口实现:声明必须兼容 [英] Interface implementation: declaration must be compatible

查看:29
本文介绍了接口实现:声明必须兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接口:

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 中做到这一点?

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;
}

这篇关于接口实现:声明必须兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆