Call parent constructor automatically after children PHP

iLevi picture iLevi · May 9, 2013 · Viewed 12.2k times · Source

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.

Answer

Marc B picture Marc B · May 9, 2013

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).