我试图为返回B类实例的A类和B类本身指定两个接口。
我在接口上声明返回类型。
假设我有两个接口。
某种类型的RepositoryInterface,它有一个返回实现ElementInterface的对象的get()方法。
<?php
namespace App\Contracts;
interface RepositoryInterface {
public function get( $key ) : ElementInterface;
}和元素接口:
<?php
namespace App\Contracts;
interface ElementInterface { }现在,我的存储库实现声明了一个返回类型,它是一个特定的类MyElement。
<?php
namespace App\Repositories;
class MyRepository implements RepositoryInterface {
public function get( $key ) : MyElement {
// ...
}
}其中MyElement是一些实现ElementInterface的类。
..。这将导致致命错误:
Declaration of MyRepository::get( $key ): MyElement must be compatible with RepositoryInterface::get( $key ): ElementInterface如果我不指定接口上的返回类型,这将非常好。但是,我希望约束实现RepositoryInterface的任何类返回的类的类型。
发布于 2018-03-18 21:37:58
如果PHP的任何版本低于7.4,这是不可能的。
如果您的接口包含:
public function get( $key ) : ElementInterface;那么你的课需要:
class MyRepository implements RepositoryInterface {
public function get( $key ) : ElementInterface {
returns new MyElement();
// which in turn implements ElementInterface
}
}实现接口的类的声明必须与完全匹配,与接口所规定的契约完全匹配。
通过声明它必须返回一个特定的接口而不是一个特定的实现,您可以在如何实现它方面有回旋余地(现在您可以返回MyElement或AnotherElement,只要两者都实现了ElementInterface);但是方法声明必须是相同的。
看到它在运行这里。
从PHP7.4开始,将于2019年11月发布,返回类型将支持协方差。。到那时,这个方法就能成功了。
https://stackoverflow.com/questions/49352636
复制相似问题