【问题标题】:Why is this declaration not compatible?为什么这个声明不兼容?
【发布时间】:2013-07-15 19:46:42
【问题描述】:

总之我有

abstract class AbstractMapper implements MapperInterface {

    public function fetch(EntityInterface $entity, Array $conditions = array()) {
        . . .
    }

}

interface MapperInterface {

    public function fetch(EntityInterface $entity, Array $conditions = array());

}

abstract class AbstractUserMapper extends AbstractMapper implements UserMapperInterface {

    public function fetch(UserInterface $user, Array $conditions = array()) {

        $conditions = array_merge($conditions, array('type' => $user->getType()));

        return parent::fetch($user, $conditions);
    }

}

interface UserMapperInterface {

    public function fetch(UserInterface $user, Array $conditions = array());

}

这是我得到的错误:

致命错误:Model\Data\Mappers\AbstractUserMapper::fetch() 的声明必须与 Model\Data\Mappers\Interfaces\MapperInterface::fetch() 的声明兼容

如果我将 UserInterface 更改为 EntityInterface 它可以工作,但它似乎是错误的,而且在我的 AbstractUserMapper::fetch() 中,当我键入$user 时,我的 IDE 仅显示在我的 EntityInterfacegetType() 中声明的方法不在该列表中。

我知道我仍然可以输入 $user->getType(),因为我知道我拥有的对象实现了 UserInterface 但这一切似乎都是错误的,甚至我的 IDE 也这么认为还是我在这里遗漏了什么?

为什么这不起作用?如果我必须输入 EntityInterface 而不是 'UserInterface 我想,这会弄乱我的代码。

【问题讨论】:

  • 这可能是因为您的 AbstractUserMapper 扩展了 AbstractMapper 但您的 fetch() 函数不匹配。也许尝试添加一个 fetchUser() 方法而不是相同的函数名称
  • 接口是关于你支持什么的契约,你不能说“第一个参数是EntityInterface,第一个参数是UserInterface。”。您期望/要求第一个参数具有EntityInterface 功能或UserInterface 功能。事实是,如果您需要 AbstractUserMapper::fetch() 中的UserInterface,那么它只是不实现MapperInterface::fetch(),因为它必须是能够处理 any EntityInterface,而不仅仅是 UserInterface 那些...
  • 难道你不认为如果 UserInterface 扩展了 EntityInterface 它会让我做我想做的事情,因为它会知道 UserInterface 也具有 EntityInterface 的功能并且应该没有问题据我所知。这只是 PHP 的事情吗?
  • PHP 不支持方法重载...仅方法覆盖,因此您不能在具有给定名称的类上拥有一个以上的方法,这是您必须满足两者的要求的接口。
  • 举个例子:你正在经营一家电视维修店,宣传“我们可以修理任何电视”,然后你继续要求人们只给你等离子电视,因为你不能与其他人一起工作。 “我们可以修理任何电视” 的口号不再适用,您只能修理等离子电视,应该这样做广告。

标签: php oop


【解决方案1】:

问题出在这里:

abstract class AbstractUserMapper 
  extends AbstractMapper 
  implements UserMapperInterface 

第一步,检查AbstractMapper的定义:

abstract class AbstractMapper 
  implements MapperInterface

父类和子类之间的接口定义是传递的,所以我们可以合并第一个定义:

abstract class AbstractUserMapper 
  extends AbstractMapper 
  implements UserMapperInterface, MapperInterface

这意味着你的类需要实现:

public function fetch(EntityInterface $entity, Array $conditions = array());

public function fetch(UserInterface $user, Array $conditions = array());

这是不可能的,因为 PHP 中不存在方法重载。

可能的解决方案

假设以下接口定义:

interface EntityInterface {}
interface UserInterface extends EntityInterface {}

我建议放弃implements UserMapperInterface:

abstract class AbstractUserMapper extends AbstractMapper

【讨论】:

    猜你喜欢
    • 2012-12-02
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 2022-12-13
    相关资源
    最近更新 更多