Call parent constructor automatically after children PHP

14,450

Solution 1

As per the documentation: http://php.net/manual/en/language.oop5.decon.php

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. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Solution 2

By default, parent constructors are never called automatically (unless defined in the child classes). Even in Java, you have to call them explicitly and it must be the first statement.

Note, that in PHP the name of constructor function is __construct and it is supposed to be a magic method, because it is called when an object is created.

class LukeSkywalker extends DarthVader{
  public function __construct(){ //See the name of magic  method. It is __construct
    parent::__construct(); //Call parents constructor
    echo "- He told me enough! He told me you killed him!\n"
    $this->response();
  }
}

Use the code above and you will get the desired result each time you perform:

new LukeSkywalker();

Share:
14,450
iLevi
Author by

iLevi

I don't know what i know

Updated on June 05, 2022

Comments

  • iLevi
    iLevi almost 2 years

    I was tried with the name of parent class like constructor and works partially for me.

    First calls to

    "DarthVader method"

    like constructor but never call to

    "LukeSkywalker constructor"..

    somebody knows how do it?

    example:

    Darth.php

    class DarthVader{
        public function DarthVader(){
            echo "-- Obi-Wan never told you what happened to your father.\n";
        }
        public function reponse(){
            echo "-- No. I am your father\n";
        }
    }
    

    Luke.php

    include("Darth.php")
    
    class LukeSkywalker extends DarthVader{
     public function __constructor(){
            echo "- He told me enough! He told me you killed him!\n"
            $this->response();
        }
    }
    

    Expected result:

    • Obi-Wan never told you what happened to your father.

    • He told me enough! He told me you killed him!

    • No. I am your father

    I really would like it to so, automatically.