【发布时间】:2017-05-17 15:05:32
【问题描述】:
我有一个父类A 和一个子类B。我现在的目标是初始化content(A 的属性)。只有B 知道应该进入A::content 的值。
class A
{
protected $m;
protected $n;
protected $p;
protected $content;
public function __construct() {
$this->init();
$b = new B;
$this->content = $b->getContent();
}
private function init() {
$this->m = 'Nobody';
$this->n = 'is';
$this->p = 'like';
}
public function getContent() {
return $this->content;
}
}
class B extends A
{
protected $x;
public function __construct() {
$this->init();
$this->content = $this->m.' '.$this->n.' '.$this->p.' '.$this->x.' (according to '.$this->x.')';
}
private function init() {
$this->x = 'Donald Trump';
}
}
$a = new A;
echo $a->getContent();
在我的项目中,我有一些类 - 比如说 B、C、D(它们在上面的代码中看起来像 B)。它们都有一个共同点:需要A的变量和方法来设置A::content的值。
我现在的问题是:这是实现目标的“好”方式吗?另一种选择可能是不使用继承,而是将A 的实例注入B 的构造函数中...或者其他替代方法?
编辑:
好吧......看起来我无法让自己清楚。不幸的是,我的英语不够好,无法使我的观点更清楚。
我是 OOP 的新手,我并不想了解所有 S.O.L.I.D.原则。我正在努力理解
1. 我在哪里?
2. 我想去哪里?
3. OOP 如何帮助我到达那里?
编辑: 在我的真实项目中,我正在实例化父级(代码的最后两行)。父母决定(通过解析 $_GET)要实例化哪个孩子:B、C 或 D
感谢@A.P.的提示,我通过更改B的构造函数解决了这个问题
public function __construct() {
parent::init();
$this->init();
$this->content = $this->m.' '.$this->n.' '.$this->p.' '.$this->x.' (according to '.$this->x.')';
}
【问题讨论】:
-
A(父母)不应该知道 B(孩子)。你正在扭转关系。 A 是独立的,不需要子类。 B 是依赖的,需要父类。在您的设计中,孩子是独立的,父母是依赖的。
-
我相信你应该研究一下抽象类,这样你就可以为你的所有类定义相同的方法,你已经探索过这种方式了吗?
-
你不应该在构造函数中使用 new,因为它是隐藏的依赖。但我不确定你想在这里完成什么。您可以根据需要更改 A 和 B 的代码吗?例如将 init() 方法的可见性更改为 public/protected?
标签: php oop inheritance dependency-injection