PHP: propagation of constructors or moving constructor to a concrete child

时间:2016-05-11 11:32:54

标签: php oop

Suppose there is AbstractClass:

abstract class AbstractClass {

    protected $fooClass;

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

    public function bar()
    {
        $this->fooClass->baz();
    }
}

AbstractClass has a couple of children (1st generation) and these children have their own children (2nd generation). All children are concrete classes.

I want to use the bar() method of the AbstractClass in a child of the 2nd generation. My first guess is to propagate constructors from 2nd generation to 1st with parent::__construct($fooClass);. Not sure if it's good.

If I move the constructor of AbstractClass into a child of the 2nd generation, can I call the bar() method from that child?

Or is there a better way of doing this?

1 个答案:

答案 0 :(得分:1)

来自http://php.net/manual/en/language.oop5.decon.php

  

如果子类定义了构造函数,则不会隐式调用父构造函数。为了运行父构造函数,需要在子构造函数中调用parent :: __ construct()。如果子进程没有定义构造函数,那么它可以像普通的类方法一样从父类继承(如果它没有被声明为私有)。

这意味着有2个选项:

  1. 不要为子项定义任何构造函数(在大多数情况下可能不可行),并假设所有子项都只存在抽象类构造函数。
  2. 在每个子构造函数中调用parent::__construct(推荐)
  3. 只要方法bar()未在任何子类中被重写,它就可以像类方法一样被调用,并将引用抽象类方法bar()