The __CLASS__
magic constant is not interpreted as being whatever the concrete class an instance is, but instead evaluates to the class name that the constant is contained in.
If you want to get the concrete class name (rather than the base class name), try using get_class()
instead.
<?php
class A
{
public function test1()
{
echo __CLASS__ . "
";
}
public function test2()
{
echo get_class($this) . "
";
}
}
class B extends A {}
$b = new B;
$b->test1();
$b->test2();
Output:
A
B
Update
In your particular situation, there are only two awesome
methods; one defined on generation2
and one defined on generation1
. generation3
and generation4
rely on their ancestor's definitions, and thus are not actually called inside of their context (this is why you only see two outputs, there's only two methods called).
You could get around this by defining the awesome
method at every level like you have it written. The trouble then is the $this->whoami()
line. $this
in each of those contexts is referring to a concrete instance of a generation4
object, so even at the generation2
level calling $this->whoami()
inside of the awesome method will cause the method on generation4
to be called from all of the awesome
methods.
You can get around this limitation, too, by changing $this
to be self
. The final solution which I was able to come up with is this:
class gen1
{
public function whoami()
{
echo __CLASS__ . PHP_EOL;
}
public function awesome()
{
self::whoami();
}
}
class gen2 extends gen1 {
public function whoami()
{
echo __CLASS__ . PHP_EOL;
}
public function awesome()
{
self::whoami();
parent::awesome();
}
}
class gen3 extends gen2 {
public function whoami()
{
echo __CLASS__ . PHP_EOL;
}
public function awesome()
{
self::whoami();
parent::awesome();
}
}
class gen4 extends gen3 {
public function whoami()
{
echo __CLASS__ . PHP_EOL;
}
public function awesome()
{
self::whoami();
parent::awesome();
}
}
$gen4 = new gen4;
$gen4->awesome();
Which gives an output of:
gen4
gen3
gen2
gen1
You may be able to get around some of these limitations if you have PHP 5.5 installed (I am only on 5.4 locally right now, can't test this), but see this answer for some other possibilities.