在运行时而不是编译时绑定的__CLASS__的版本 [英] Version of __CLASS__ that binds at run-time rather than at compile-time

查看:122
本文介绍了在运行时而不是编译时绑定的__CLASS__的版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的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 this without 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

推荐答案

您可以简单地使用

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__的版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆