Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call parent constructor automatically after children PHP

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.

like image 450
iLevi Avatar asked May 09 '13 19:05

iLevi


People also ask

Does PHP automatically call parent constructor?

The fact that PHP always calls the "nearest" constructor, that is if there is no child constructor it will call the parent constructor and not the grandparent constructor, means that we need to call the parent constructor ourselves. We can do this by using the special function call parent::__construct().

How do you call a constructor of parent class from child class?

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). $obj = new OtherSubClass();

Does child constructor call parent constructor?

If parent class implements a constructor with arguments and has no a constructor with no arguments, then the child constructors must explicitly call a parents constructor.

Does child inherit parent constructor?

Child classes inherit accessible fields and methods from their parent classes and other ancestors. They never inherit constructors, however.


1 Answers

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

like image 161
Marc B Avatar answered Sep 28 '22 17:09

Marc B