php - 如何优化我的特征代码以避免在子类中具有相同值的两个属性
问题描述
我有这段代码,但我觉得有些不对劲。我必须为两个不同的属性分配相同的值。一个来自我的特质,另一个来自我现在的班级。
我希望我可以完全隔离我的特征,而不必在我的子类构造函数中进行此分配。
代码:
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();
}
}
别担心,智能感知仍然有效。
推荐阅读
- javascript - 使用超时来实现跳转功能
- ruby - 试图剔除一个集合,但集合不断消失
- javascript - 为什么必须在 componentDidMount() 期间解析函数中的函数调用?
- wpf - 当目标应用程序移动到第二台显示器时,为什么我的应用程序包含 DWM 缩略图滞后?
- opengl - 无法用鼠标选择在帧缓冲区中渲染的四边形
- python - 具有 **kwargs 输出的类:未定义 arg
- python - 我可以在识别段落中的给定单词时使用自然语言处理还是需要使用机器学习算法
- mysql - 如何计算查询结果
- php - Laravel:无法打开蒸汽:没有这样的文件或目录
- java - 我有错误:“javac.exe”以代码 3 退出