2012-10-28 37 views
1

这里是一个代码:腓:错误的方法调用,在错误的抽象层次

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; 

CcallItself()不能被调用,因此它丢弃异常。我不能把它设置为私人,因为我们知道:)但在10行,$this->callItself();调用**C**而不是A的方法,因此它死亡。但我不想要它,如何躲避?的$this->callItself();

回答

2

使用self::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)