Ok, so I made this and thought others might find it useful. The funtion will return your child class.
<?php
function get_called_class()
{
$objects = array();
$traces = debug_backtrace();
foreach ($traces as $trace)
{
if (isset($trace['object']))
{
if (is_object($trace['object']))
{
$objects[] = $trace['object'];
}
}
}
if (count($objects))
{
return get_class($objects[0]);
}
}
class Base1
{
public function test()
{
echo get_called_class() . '<br />';
}
}
class Base2 extends Base1 {}
class Base3 extends Base2 {}
$b1 = new Base1();
$b1->test();
$b2 = new Base2();
$b2->test();
$b3 = new Base3();
$b3->test();
?>
Since you are only returning one result and is the first. You can skip everything else and just return the first object it encounters.
if ( function_exists( 'get_called_class' ) ) {
function get_called_class ()
{
foreach ( debug_backtrace() as $trace ) {
if ( isset( $trace['object'] ) )
if ( $trace['object'] instanceof $trace['class'] )
return get_class( $trace['object'] );
}
return false;
}
}
Edit!
Since the class that is calling would be the first result anyways.
if ( function_exists( 'get_called_class' ) ) {
function get_called_class ()
{
$t = debug_backtrace(); $t = $t[0];
if ( isset( $t['object'] ) && $t['object'] instanceof $t['class'] )
return get_class( $t['object'] );
return false;
}
}
True, though my actual implementation passes in ($depth = 0) and uses $objects[$depth]. But I didn’t think about simply using instanceof. I’ll have to fix that.