在 运行 时而不是在编译时绑定的 __CLASS__ 版本
Version of __CLASS__ that binds at run-time rather than at compile-time
在下面的 PHP 代码中,我想用函数 __X__()
(或其他东西)替换 Foo
class 中的 __CLASS__
魔法常量类似),因此当从 Bar
class 的实例 $bar
调用方法 hello()
时,它会打印 hello from Bar
(而不是 hello from Foo
).我想这样做
无需覆盖 Bar
.
内的 hello()
所以基本上,我想要一个 __CLASS__
的版本,它在 运行 时而不是在编译时动态绑定。
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()
):
hello from Bar
world from Bar
您可以简单地使用 get_class()
,像这样:
echo "hello from " . get_class($this) . "\n";
echo "world from " . get_class($this) . "\n";
输出:
hello from Bar
world from Bar
在下面的 PHP 代码中,我想用函数 __X__()
(或其他东西)替换 Foo
class 中的 __CLASS__
魔法常量类似),因此当从 Bar
class 的实例 $bar
调用方法 hello()
时,它会打印 hello from Bar
(而不是 hello from Foo
).我想这样做
无需覆盖 Bar
.
hello()
所以基本上,我想要一个 __CLASS__
的版本,它在 运行 时而不是在编译时动态绑定。
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()
):
hello from Bar
world from Bar
您可以简单地使用 get_class()
,像这样:
echo "hello from " . get_class($this) . "\n";
echo "world from " . get_class($this) . "\n";
输出:
hello from Bar
world from Bar