如何优化我的特征代码,以避免在子类中有两个相同值的属性



我有这段代码,但我觉得有些不对劲。事实上,我必须为两个不同的属性分配相同的值。一个来自我的特点,另一个来自目前的班级。

我希望我能完全隔离我的特质,而不必在我的孩子类构造函数中做这个作业。

代码:

interface ARepoInterface extends BaseRepoInterface {}
interface BRepoInterface extends BaseRepoInterface {}

trait Foo {
protected BaseRepoInterface $repo;
public function method(array $array): void {
// Do stuff with $repo
}
}
class A
{
private ARepoInterface $ARepo;
protected BaseRepoInterface $repo;
use Foo;
public function __construct(ARepoInterface $ARepo)
{
//@todo This is weird
$this->ARepo = $this->repo = $ARepo;
}
//Other methods
}
class B
{
private BRepoInterface $BRepo;
protected BaseRepoInterface $repo;
use Foo;
public function __construct(BRepoInterface $BRepo)
{
//@todo This is weird
$this->BRepo = $this->repo = $BRepo;
}
//Other methods
}

提前感谢您的建议

事实上,PHP并不太关心类型提示,所以一个属性就足够了。

interface ARepoInterface extends BaseRepoInterface { public function A(); }
class A
{
use Foo;
public function __construct(ARepoInterface $ARepo)
{
$this->repo = $ARepo;
}
public function methodDoStuffWithARepoInterface()
{
$this->repo->A();
}
}

别担心,智能感知仍然有效。

最新更新