【问题标题】:Setting parent variable from child class从子类设置父变量
【发布时间】: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


【解决方案1】:

以下是我的更正,以使您正在尝试做的工作。但是,您不能创建 A 类并期望它从 B 类(这是一个孩子)获取数据 但是可以从B类中访问A类的构造函数

    class A
{
    protected $m;
    protected $n;
    protected $p;
    protected $content;

    public function __construct() {
        $this->init();
    }

    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() {
        parent::__construct();
        $this->init();
        $this->content = $this->m.' '.$this->n.' '.$this->p.' '.$this->x.' (according to '.$this->x.')';
    }

    private function init() {

        $this->x = 'Donald Trump';
    }

     public function getContent() {
        return $this->content;
    }
}

$B = new B;
echo $B->getContent();

【讨论】:

  • 您的示例有效...并且使用父构造函数是一个很好的提示。谢谢。我没有提到的:在我的真实项目中,我正在实例化 A。A 决定(通过解析 $_GET)要实例化哪个孩子:B、C 或 D。我无法实例化 B(代码的最后两行)因为我不知道我需要它的 B、C 还是 D。
  • “你不能创建一个 A 类并期望它从 B 类获取数据”——我可以而且我会 ;-)
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多