2012-09-25 48 views
8

可能重複:
How do I get a PHP class constructor to call its parent's parent's constructor如何跳過執行父方法來執行祖父方法?

我知道這聽起來很奇怪,但我試圖繞過一個bug。我怎樣稱呼祖父母方法?

<?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

你有過在層次結構類的控制? –

回答

10

你可以直接調用它;

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

parent僅僅是使用最近的基類,而不在多個地方使用基類的名稱,但提供任何基類的類名的作品一樣好使用,代替直接父的方式。

1

PHP有本地的方式來做到這一點。

試試這個:

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();