Php 定义继承和多态性时不兼容类型的异常
我定义了一个DTO类,然后又定义了一个扩展自第一个DTO类的DTO类Php 定义继承和多态性时不兼容类型的异常,php,oop,Php,Oop,我定义了一个DTO类,然后又定义了一个扩展自第一个DTO类的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
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
}
}
我在函数create中遇到一个关于不兼容类型的错误
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,因为第二个继承了第一个。最后,我通过更改“create”方法的签名并将参数设置为DTO类来解决这个问题。像这样:
namespace App\DTO;
class DTO {};
namespace App\Modules\Auth\User\DTO;
class DTO extends App\DTO\DTO {
...Some definitions here
}
namespace App\Modules\Auth\Repository;
class UserRepository implements App\Interfaces\iRepository {
public function create(App\DTO\DTO $data) {
...some code here
}
}
这样,我可以使用SignUpDTO作为参数调用create方法