【问题标题】:Exception on incompatible types when defining inheritance and polymorphism [duplicate]定义继承和多态时不兼容类型的异常[重复]
【发布时间】:2019-06-25 18:04:55
【问题描述】:

我已经定义了一个 DTO 类,然后,另一个从第一个扩展而来。

namespace App\DTO;

class DTO {};

namespace App\Modules\Auth\User\DTO;

class DTO extends App\DTO\DTO {

...Some definitions here

}

接下来我创建了一个通用的存储库接口;

namespace App\Interfaces;

interface iRepository {

   public function create(App\DTO\DTO $data);

}

最后,我的用户模型的类存储库;

namespace App\Modules\Auth\Repository;   

class UserRepository implements App\Interfaces\iRepository {

   public function create(App\Modules\Auth\DTO\SignUpDTO $data) {

      ...some code here
   }
}

我收到关于函数创建中不兼容类型的错误。

Symfony\Component\Debug\Exception\FatalErrorException:App\Modules\Auth\Repository\UserRepository::create(App\Modules\Auth\DTO\SignUpDTO $data) 的声明必须与 App\Interfaces\RepositoryInterface 兼容: :create(App\DTO\DTO $object)

我认为多态性意味着我可以同时使用 App\DTO\DTO 和 App\Modules\Auth\DTO\SignUpDTO,因为第二个继承了第一个。

【问题讨论】:

    标签: php oop


    【解决方案1】:

    最后,我通过更改“create”方法的签名并将 DTO 类设置为参数来解决这个问题。像这样:

    namespace App\Modules\Auth\Repository;   
    
    class UserRepository implements App\Interfaces\iRepository {
    
       public function create(App\DTO\DTO $data) {
    
          ...some code here
       }
    }
    

    这样我可以使用 SignUpDTO 作为参数调用 create 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 2019-10-22
      • 2012-07-14
      • 1970-01-01
      • 2018-05-29
      • 2012-02-17
      • 1970-01-01
      相关资源
      最近更新 更多