2017-02-12 63 views
2

我想了解为什么我无法在我的代码中执行此操作?(DI)为什么我不能在我的PHP代码中执行此操作

<?php 
Class Model 
{ 
    protected static function insert(Entity $entity) 
    { 
      # some codes to insert data in the database 
    } 
} 

<?php 
Class UserModel extends Model 
{ 

    protected static function insert(UserEntity $entity) 
    { 
     parent::insert($entity); 
    } 
} 

基本上UserEntity也是实体为什么PhpStorm都跟我 “申报应与型号 - 兼容>插入(单位:\实体)

回答

1

即使UserEntity当您更改方法签名时扩展实体:

protected static function insert(Entity $entity) 

至:

protected static function insert(UserEntity $entity) 

Model和UserModel不再兼容。你可以做的是这样的:

protected static function insert(Entity $entity) 
{ 
    if (!$entity instanceof UserEntity) { 
     return \InvalidArgumentException('Entity must be a UserEntity'); 
    } 
    ... 
} 

有人可能认为,通过要求子对象,而不是一个定义毁约突破了接口隔离原则。无论如何,这些方法不再匹配,因为你的方法表明它不再只需要一个实体,因此可能不兼容。

编辑:目前有一个建议,你正在尝试做什么。它被称为Parameter Type Widening

相关问题