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

1

0

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
Muscadel answered 9/2, 2015 at 0:53 Comment(0)
R
2

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
Rese answered 9/2, 2015 at 0:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.