claude noted that __CLASS__ always contains the class that it is called in, if you would rather have the class that called the method use get_class($this) instead. However this only works with instances, not when called statically.
<?php
class A {
function showclass() {
echo get_class($this);
}
}
class B extends A {}
$a = new A();
$b = new B();
$a->showclass();
$b->showclass();
A::showclass();
B::showclass();
//results in "a", "b", false, false
?>
I tried keeping track of the class manually within the properties, but the following doesn't work either:
<?php
class A {
var $class = __CLASS__;
function showclass() {
echo $this->class;
}
}
class B extends A {
var $class = __CLASS__;
}
//results in "a", "b", NULL, NULL
?>
The best solution I could come up with was using debug_backtrace. I assume there is a better way somehow, but I can't find it. However the following works:
<?php
class A {
function showclass() {
$backtrace = debug_backtrace();
echo $backtrace[0]['class'];
}
}
class B extends A {}
//results in "a", "b", "a", "b"
?>