Version of __CLASS__ that binds at run-time rather than at compile-time

独自空忆成欢 提交于 2019-12-13 05:43:22

问题


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.

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();

OUTPUT:

hello from Foo
world from Bar

I WANT THIS OUTPUT (without overriding hello() inside Bar):

hello from Bar
world from Bar

回答1:


You could simple use get_class(), like this:

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

Output:

hello from Bar
world from Bar


来源:https://stackoverflow.com/questions/28401274/version-of-class-that-binds-at-run-time-rather-than-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!