2012-10-28 64 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)