2013-12-12 57 views
1
class parent 
{ 
    public function methodInParentClass() 
    { 
     echo "In parent class called from child class of:"; 
    } 
} 

class childOne extends parent 
{ 
    public $childProperty = "in childOne property"; 
} 

class childTwo extends parent 
{ 
    public $childProperty = "in childTwo property"; 
} 

好的,所以我們有兩個子類都擴展了父類。現在,如果我叫確定哪個子類正在調用父類'方法

childTwo->methodInParentClass() 

問題:

1)methodInParentClass如何確定是哪個類調用它?請注意:通過變量傳入名稱不可用。 2)如果#1是可以實現的,我怎樣稱呼孩子的班級資產?我可以實例化一個新類,然後從中調用它,但不會有一些性能問題(特別是因爲我的項目可能會這樣做很多)?

在此先感謝!

回答

2

你的問題實際上沒有什麼意義。讓我來解釋:

1)是的,你可以確定與get_class($this)調用父類的方法當前類:

public function methodInParentClass() 
{ 
    echo "In parent class called from child class of:".get_class($this); 
} 

2)(這是爲什麼我懷疑感)。請注意,例如,在調用某種方法時,例如,因爲您已發佈$childTwo->methodInParentClass(),其中$childTwochildTwo類的實例 - 您將使用childTwo上下文執行此操作。因此,所有「孩子」屬性將是當前實例的屬性,即可通過變量$this訪問。

+0

嗯......我誤讀了get_class的文檔,並且覺得它會返回「父」類/屬性。我的錯。 –