簡體   English   中英

PHP:使用擴展類中的繼承函數調用類名

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM