2012-10-28 2 views
1

est ici un code:Php: méthodes erronées appelées, au mauvais niveau d'abstraction

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; 

en classe C le callItself() ne doit pas être appelé, il laisse tomber une exception. Je ne peux pas le rendre privé comme nous le savons :) mais à 10 lignes, le $this->callItself(); appelle cette méthode de **C** au lieu de A donc il meurt. Mais je ne le veux pas, comment esquiver ça?

Répondre

2

Utilisation self::callItself() au lieu de $this->callItself();

Remplacer

public function callItself() 
{ 
    echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>'; 
    if (rand(1,100) == 5) { die; } 
    $this->callItself(); 
} 

Avec

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 
} 

Sortie

C:add (23) 
B:add (17) 
A:callItself (7) 
A:callItself (7) 
A:callItself (7) 
A:callItself (7) 
A:callItself (7) 
A:callItself (7) 
Questions connexes