iLe*_*evi 10 php oop inheritance constructor parent-child
我尝试使用类构造函数的父类的名称,并为我部分工作.
第一次打电话给
"DarthVader方法"
像构造函数但从不打电话给
"LukeSkywalker构造函数"..
有人知道怎么做?
例:
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";
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
预期结果:
欧比万从未告诉过你父亲发生了什么事.
他告诉我够了!他告诉我你杀了他!
不,我是你的父亲
我真的很想这样,自动.
Mar*_*c B 29
根据文档:http://php.net/manual/en/language.oop5.decon.php
注意:如果子类定义构造函数,则不会隐式调用父构造函数.为了运行父构造函数,需要在子构造函数中调用parent :: __ construct().如果子节点没有定义构造函数,那么它可以像普通类方法一样从父类继承(如果它没有被声明为私有).