2015-02-08 86 views
2
class Grandfather { 

    protected function stuff() { 
     // Code. 
    } 
} 

class Dad extends Grandfather { 
    function __construct() { 
     // I can refer to a member in the parent class easily. 
     parent::stuff(); 
    } 
} 

class Kid extends Dad { 
     // How do I refer to the stuff() method which is inside the Grandfather class from here? 
} 

我如何從Kid類中引用祖父類的成員?是否有一個引用PHP中祖父類成員的關鍵字?

我的第一個想法是Classname::method()但有沒有關鍵字可用,如selfparent

+2

您是否嘗試過parent :: parent :: stuff()? – 2015-02-08 11:35:47

+0

我還沒有嘗試過'parent :: parent :: stuff()'。你有任何進一步的信息嗎? – henrywright 2015-02-08 11:45:56

+0

它不會工作@NomanUrRehman,它會像這樣casue語法錯誤:'PHP解析錯誤:語法錯誤,意外的'::'(T_PAAMAYIM_NEKUDOTAYIM)' – 2015-02-08 11:46:34

回答

3
  1. 如果stuff()類層次是行不通重寫你可以調用與$this->stuff()
  2. 功能如果stuff()Dad被重寫你必須調用與類名,例如功能Grandfather::stuff()
  3. 如果stuff()Kid重寫,你可以如果你想叫爺爺::東西方法,你可以在Kid類做到這一點使用Grandfather::stuff()通過parent::stuff()
+3

你的課程是從「祖父」開始延伸的,因此你繼承了「祖父」的所有屬性 - 即這將在祖父 – Tyron 2015-02-08 11:38:13

+0

中調用stuff()函數,但是如果我在'Kid '?我需要參考祖父班的方法。你明白我的意思嗎? – henrywright 2015-02-08 12:01:30

+0

然後,你必須使用'祖父::東西()'作爲其他人已經提到這裏。雖然在我看來這不是一個很乾淨的方式 - 你的意圖是什麼?也許一個不同的設計模式會給你一個更好的解決方案。 – Tyron 2015-02-08 12:09:28

1

做呼叫。

看看這個example

+0

所以你必須使用'Class_Name :: method()'?我想我的問題應該是有一個像'parent'和'self'這樣的關鍵字,當你指向層次結構上的多個關卡時? – henrywright 2015-02-08 11:42:26

5

$this->stuff()Grandfather::stuff()

與此調用將調用::stuff()方法上繼承層次 的頂部(在您的示例它會是Dad::stuff(),但你不Dad類中重寫::stuff所以」 d爲Grandfather::stuff()

Class::method()和將調用確切類方法

實施例的代碼:

<?php 
class Grandfather { 

    protected function stuff() { 
     echo "Yeeeh"; 
     // Code. 
    } 
} 

class Dad extends Grandfather { 
    function __construct() { 
     // I can refer to a member in the parent class easily. 
     parent::stuff(); 
    } 
} 

class Kid extends Dad { 
    public function doThatStuff(){ 
     Grandfather::stuff(); 
    } 
     // How do I refer to the stuff() method which is inside the Grandfather class from here? 
} 
$Kid = new Kid(); 
$Kid->doThatStuff(); 

「Yeeeh」將被輸出2次。因爲構造函數Dad(它在Kid類中沒有被忽略)類調用Grandfather::stuff()Kid::doThatStuff()也稱它爲

+0

感謝您的回答。從我+1 – henrywright 2015-02-08 12:37:50

相關問題