这是一个代码:
abstract class A
{
abstract public function add();
public function callItself()
{
echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
if (rand(1,100) == 5) { die; }
$this->callItself();
}
}
class B extends A
{
public function add()
{
echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
}
}
class C extends B
{
public function add()
{
echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
parent::add();
parent::callItself();
}
public function callItself()
{
echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
throw new Expection('You must not call this method');
}
}
$a = new C();
$a->add();
die;
在课程C
中,不得调用callItself()
,因此会丢弃异常。我不能将它设置为私有我们知道:)但是在10行,$this->callItself();
调用**C**
而不是A
的方法,因此它会死掉。但我不想要它,如何避开它?
答案 0 :(得分:2)
使用self::callItself()
代替$this->callItself();
替换
public function callItself()
{
echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
if (rand(1,100) == 5) { die; }
$this->callItself();
}
使用
public function callItself() {
echo __CLASS__ . ':' . __FUNCTION__ . ' (' . __LINE__ . ')<br>';
if (rand(0, 2) == 0) { <------- Better Probability
die();
}
self::callItself(); <---- This would continue to call A:callItself until die
}
输出
C:add (23)
B:add (17)
A:callItself (7)
A:callItself (7)
A:callItself (7)
A:callItself (7)
A:callItself (7)
A:callItself (7)