PHP:使用扩展类中的继承函数调用类名

时间:2011-09-06 15:43:01

标签: php class inheritance

如果有效,我正在进行中:

    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”,但我总是得到父类。 我在这里有点失落。我怎样才能让这段代码正常工作?

3 个答案:

答案 0 :(得分:1)

get_class()返回'Foo',因为Spoon()方法是继承的,所以它在Foo类中执行。 使用__CLASS__常量而不是get_class()应该可以按照您的意愿使用。

答案 1 :(得分:1)

尝试:

echo parent::Spoon();

这会强制它在父类(Foo)的上下文中引用。您也可以在Bar内使用get_parent_class()

echo get_parent_class('Bar');

答案 2 :(得分:1)

你可以像in this answer那样使用后期静态绑定(php> = 5.3)。

protected function Spoon() {
    get_called_class($this);
}

或使用

调用该函数
$this->Spoon();