2012-09-25 9 views
8

Eventuali duplicati:
How do I get a PHP class constructor to call its parent's parent's constructorCome saltare l'esecuzione di un metodo genitore per eseguire il metodo grandparent?

So che sembra strano, ma sto cercando di aggirare un bug. Come posso chiamare un metodo per nonni?

<?php 
class Person { 
    function speak(){ echo 'person'; } 
} 
class Child extends Person { 
    function speak(){ echo 'child'; } 
} 
class GrandChild extends Child { 
    function speak(){ 
     //skip parent, in order to call grandparent speak method 
    } 
} 
+0

Hai il controllo su tutte le classi nella gerarchia? –

risposta

10

Si può semplicemente chiamarlo esplicitamente;

class GrandChild extends Child { 
    function speak() { 
     Person::speak(); 
    } 
} 

parent è solo un modo per utilizzare la classe di base più vicino senza utilizzare il nome della classe base in più di un luogo, ma dare alcuna nome di classe della classe di base funziona altrettanto bene da usare che al posto del padre immediato .

1

PHP ha un modo nativo per farlo.

provare questo:

class Person { 

    function speak(){ 

     echo 'person'; 
    } 
} 

class Child extends Person { 

    function speak(){ 

     echo 'child'; 
    } 
} 

class GrandChild extends Child { 

    function speak() { 

     // Now here php allow you to call a parents method using this way. 
     // This is not a bug. I know it would make you think on a static methid, but 
     // notice that the function speak in the class Person is not a static function. 

     Person::speak(); 

    } 
} 

$grandchild_object = new GrandChild(); 

$grandchild_object->speak(); 
Problemi correlati