【问题标题】:Version of __CLASS__ that binds at run-time rather than at compile-time在运行时而不是在编译时绑定的 __CLASS__ 版本
【发布时间】:2015-04-08 16:35:05
【问题描述】:

在下面的 PHP 代码中,我想用函数 __X__()(或类似的东西)替换 Foo 类中的 __CLASS__ 魔术常量,这样当从实例 @ 调用方法 hello()Bar 类的 987654325@,它打印 hello from Bar(而不是 hello from Foo)。我想这样做 不覆盖 hello() 内的 Bar

所以基本上,我想要一个在运行时而不是在编译时动态绑定的__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

我想要这个输出(不覆盖 hello() 内的 Bar):

hello from Bar
world from Bar

【问题讨论】:

    标签: php runtime subclass classname dynamic-binding


    【解决方案1】:

    你可以简单地使用get_class(),像这样:

    echo "hello from " . get_class($this) . "\n";
    echo "world from " . get_class($this) . "\n";
    

    输出:

    hello from Bar
    world from Bar
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      相关资源
      最近更新 更多