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.
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().
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();
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.
Child classes inherit accessible fields and methods from their parent classes and other ancestors. They never inherit constructors, however.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With