Are abstract class constructors not implicitly called when a derived class is instantiated?

前端 未结 3 1362
轻奢々
轻奢々 2021-01-30 19:38

Take this example:

abstract class Base {
    function __construct() {
        echo \'Base __construct
\'; } } class Child extends Base { funct
相关标签:
3条回答
  • 2021-01-30 20:30

    Well, I just found this in the docs:

    Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

    0 讨论(0)
  • 2021-01-30 20:39

    If you need the same behaviour as C#, that is the parent constructor gets always executed before child constructor, you could create a fake constructor class for your child classes and declare it as an abstract function in your abstract parent class.

    E.g.

    abstract class Test{
      abstract public function __childconstruct();
      public function __construct(){
        echo "SOME CODE".PHP_EOL;
        $this->__childconstruct();
      }
    }
    
    class TestExtended extends Test{
      public function __childconstruct(){
        echo "SOME OTHER CODE FROM EXTENDED CLASS".PHP_EOL;
      }
    }
    
    $a = new TestExtended();
    
    /* SOME CODE
       SOME OTHER CODE FROM EXTENDED CLASS */
    
    0 讨论(0)
  • 2021-01-30 20:40

    No, the constructor of the parent class is not called if the child class defines a constructor.

    From the constructor of your child class, you have to call the constructor of the parent's class :

    parent::__construct();
    

    Passing it parameters, if needed.

    Generally, you'll do so at the beginning of the constructor of the child class, before any specific code ; which means, in your case, you'd have :

    class Child extends Base {
        function __construct() {
            parent::__construct();
            echo 'Child __construct<br/>';
        }
    }
    


    And, for reference, you can take a look at this page of the PHP manual : Constructors and Destructors -- it states (quoting) :

    Note: Parent constructors are not called implicitly if the child class defines a constructor.
    In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

    0 讨论(0)
提交回复
热议问题