【发布时间】: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 仅显示在我的 EntityInterface 和 getType() 中声明的方法不在该列表中。
我知道我仍然可以输入 $user->getType(),因为我知道我拥有的对象实现了 UserInterface 但这一切似乎都是错误的,甚至我的 IDE 也这么认为还是我在这里遗漏了什么?
为什么这不起作用?如果我必须输入 EntityInterface 而不是 'UserInterface 我想,这会弄乱我的代码。
【问题讨论】:
-
这可能是因为您的 AbstractUserMapper 扩展了 AbstractMapper 但您的 fetch() 函数不匹配。也许尝试添加一个 fetchUser() 方法而不是相同的函数名称
-
接口是关于你支持什么的契约,你不能说“第一个参数是
EntityInterface,第一个参数是UserInterface。”。您期望/要求第一个参数具有EntityInterface功能或UserInterface功能。事实是,如果您需要AbstractUserMapper::fetch()中的UserInterface,那么它只是不实现MapperInterface::fetch(),因为它必须是能够处理 anyEntityInterface,而不仅仅是UserInterface那些... -
难道你不认为如果 UserInterface 扩展了 EntityInterface 它会让我做我想做的事情,因为它会知道 UserInterface 也具有 EntityInterface 的功能并且应该没有问题据我所知。这只是 PHP 的事情吗?
-
PHP 不支持方法重载...仅方法覆盖,因此您不能在具有给定名称的类上拥有一个以上的方法,这是您必须满足两者的要求的接口。
-
举个例子:你正在经营一家电视维修店,宣传“我们可以修理任何电视”,然后你继续要求人们只给你等离子电视,因为你不能与其他人一起工作。 “我们可以修理任何电视” 的口号不再适用,您只能修理等离子电视,应该这样做广告。