[英]PHP: Calling a class name using an inherited function from a extended class
如果有效,我正在進行中:
Class Foo {
$bar = new Bar();
protected function Spoon() {
get_class($this);
}
}
Class Bar extended Foo {
$this::Spoon(); //Should show "Bar", but instead shows "Foo"
}
我希望能夠從Spoon()中找到“ Bar”,但是我總是得到父類。 我在這里迷路了。 我如何才能使此代碼正常工作?
get_class()
返回'Foo',因為Spoon()
方法是繼承的,因此它在Foo
類中執行。 使用__CLASS__
常量而不是get_class()
應該可以__CLASS__
工作。
嘗試:
echo parent::Spoon();
這將迫使它在父類( Foo
)的上下文中被引用。 您也可以在Bar
內使用get_parent_class()
:
echo get_parent_class('Bar');
您可以像此答案中那樣使用后期靜態綁定(php> = 5.3)。
protected function Spoon() {
get_called_class($this);
}
或使用
$this->Spoon();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.