如果效果,我有这个进展:
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()
应该可以像您希望的那样工作。
你可以像这个答案那样使用后期静态绑定(php>= 5.3)
protected function Spoon() {
get_called_class($this);
}
或者用
调用函数$this->Spoon();
尝试:
echo parent::Spoon();
将强制它在父类(Foo
)的上下文中被引用。你也可以在Bar
:
get_parent_class()
echo get_parent_class('Bar');