问题描述
在下面的PHP代码中,我想将Foo
类中的__CLASS__
魔术常数替换为函数__X__()
(或类似的东西),以便从实例中调用方法hello()
时<Bar
类的c4>,它显示hello from Bar
(而不是hello from Foo
).我想这样做而不覆盖Bar
内部的hello()
.
In the following PHP code I would like to replace the __CLASS__
magic constant in the Foo
class with a function __X__()
(or something similar) so that when the method hello()
is called from an instance $bar
of the Bar
class, it prints hello from Bar
(instead of hello from Foo
). And I want to do thiswithout overriding hello()
inside Bar
.
所以基本上,我想要一个__CLASS__
的版本,该版本在运行时而不是在编译时动态绑定.
So basically, I want a version of __CLASS__
that binds dynamically at run-time rather than at compile-time.
class Foo {
public function hello() {
echo "hello from " . __CLASS__ . "\n";
}
}
class Bar extends Foo {
public function world() {
echo "world from " . __CLASS__ . "\n";
}
}
$bar = new Bar();
$bar->hello();
$bar->world();
输出:
hello from Foo
world from Bar
我想要此输出(不覆盖Bar
中的hello()
):
I WANT THIS OUTPUT (without overriding hello()
inside Bar
):
hello from Bar
world from Bar
推荐答案
您可以简单地使用 get_class()
,就像这样:
You could simple use get_class()
, like this:
echo "hello from " . get_class($this) . "\n";
echo "world from " . get_class($this) . "\n";
输出:
hello from Bar
world from Bar
这篇关于在运行时而不是编译时绑定的__CLASS__的版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!