The __CLASS__ version that is bound at run time, not at compile time

In the following PHP code, I would like to replace the magic constant __CLASS__ in the Foo class with the function __X__() (or something similar), so that when calling the hello() method from an instance of $bar of the Bar class, it prints hello from Bar (instead of hello from Foo ). And I want to do this without redefining hello() inside Bar .

Basically, I need a version of __CLASS__ that dynamically binds at runtime, not 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(); 

CONCLUSION:

 hello from Foo world from Bar 

I WANT THIS EXIT (without redefining hello() inside Bar ):

 hello from Bar world from Bar 
0
source share
1 answer

You can simply use get_class() , for example:

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

Conclusion:

 hello from Bar world from Bar 
+2
source

Source: https://habr.com/ru/post/1213422/


All Articles