我有此代码,对我来说似乎有些问题。我必须为两个不同的属性分配相同的值。一个来自我的特质,另一个来自我当前的班级。
我希望我可以完全隔离我的特质,而不必在我的子类构造函数中进行此分配。
代码:
interface ARepoInterface extends BaseRepoInterface {}
interface BRepoInterface extends BaseRepoInterface {}
trait Foo {
private BaseRepoInterface $repo;
public function method(array $array): void {
// Do stuff with $repo
}
}
class A
{
private ARepoInterface $ARepo;
use Foo;
public function __construct(ARepoInterface $ARepo)
{
//@todo This is weird
$this->ARepo = $this->repo = $ARepo;
}
//Other methods
}
class B
{
private BRepoInterface $BRepo;
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();
}
}
[不用担心,智能感知仍然有效。