PHP - extended __construct

后端 未结 3 950
广开言路
广开言路 2021-01-31 08:09

I was wondering if you could help me out..

I have two classes, one extends the other.. Class B will be extended by various different objects and used for common databas

相关标签:
3条回答
  • 2021-01-31 08:50

    I'm not sure I fully understand what you are asking, but you can call the parents construct method from the child's constructor

    parent::__construct();
    

    That's the only option I know of.

    0 讨论(0)
  • 2021-01-31 08:53

    Call parent::__construct() in a::__construct():

    class a extends b
    {
       public function __construct()
       {
           parent::__construct();
       }   
    
       public function validateStuff()
       {
          $this->insert_record();
       }
    }
    

    You can omit a's constructor altogether if you're not doing any a-specific stuff.

    0 讨论(0)
  • 2021-01-31 09:01

    The parent __construct() method defined in class b will run automatically if you instantiate child class a, unless there is a __construct() method defined in class a.

    class a extends b { 
    } 
    
    class b { 
       public function __construct() 
       { 
          echo 'In B Constructor'; 
       } 
    } 
    
    $x = new a();
    

    If a __construct() method is defined in class a, then this overrides the use of the __construct() method in class b.... it will run instead of the class b __construct() method

    class a extends b { 
       public function __construct() 
       { 
          echo 'In A Constructor'; 
       } 
    } 
    
    class b { 
       public function __construct() 
       { 
          echo 'In B Constructor'; 
       } 
    } 
    
    $x = new a();
    

    So if your child class has a __construct() method defined, then you need to explicitly call the constructor for the parent if you want to execute that as well.

    class a extends b { 
       public function __construct() 
       { 
          parent::__construct();
          echo 'In A Constructor'; 
       } 
    } 
    
    class b { 
       public function __construct() 
       { 
          echo 'In B Constructor'; 
       } 
    } 
    
    $x = new a();
    
    0 讨论(0)
提交回复
热议问题