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

前端 未结 3 1363
轻奢々
轻奢々 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: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 */
    

提交回复
热议问题