Version of __CLASS__ that binds at run-time rather

2019-09-04 05:17发布

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条回答
男人必须洒脱
2楼-- · 2019-09-04 06:10

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
查看更多
登录 后发表回答