【发布时间】:2020-02-14 16:41:54
【问题描述】:
我对这个例子有一些疑问,我做了这个简单的代码,只有两个类,一个父类和一个子类。当我执行时,子必须执行父方法,父方法可以自己执行,但程序不能执行子方法。
当我运行这个程序时,同时执行父和子。有没有防止这种情况只执行父亲的方法?
class Father{
private $element = 0; //Just to prevent recursivity
public function add($a = null){
if ($this->element == 0) {
echo "<br>I'm the father"; //Execution of fhter
$this->element = 1;
$this->add('<br> I was an accidente'); //This instruccion call both methods, parent and soon
}else{
echo "<br>But not anymore";
}
}
}
class Son extends Father{
public function add($a = null){
parent::add();
echo "<br>I'm the son";
if ($a != null) {
echo $a;
}
}
}
$son = new Son();
$son->add();
我有这些结果
I'm the father
But not anymore
I'm the son
I was an accident
I'm the son
如你所见,当我在父级上执行 $this->add() 方法时,它们会执行两个方法(父子的添加)。
有没有什么方法可以执行这段代码,这样当对父亲执行 $this->add() 时,它不会同时执行(父亲和儿子)?
换句话说,我期待下一个结果
I'm the father
But not anymore
I'm the son
I was an accident
顺便说一句:我不能修改父亲类。 谢谢
【问题讨论】:
-
将
$this->add('<br> I was an accidente');更改为self::add('<br> I was an accidente');。与stackoverflow.com/questions/23318045/… 类似的问题 -
如果我不能修改Father类...我该怎么做?谢谢你的回答!!
标签: php class inheritance methods extend