-->

Version of __CLASS__ that binds at run-time rather

2019-09-04 05:23发布

问题:

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