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