tags:

views:

20

answers:

2

I have a parent class and a children class. In a parent class I define a function f() and want to print in it name of children class that extended parent class and name of children method that called this function. I do it like that.

abstract class ParentClass {

  public function f() {
       $backtrace = debug_backtrace();      
       echo "Class: " . $backtrace[1]['class']) . "\n";
       echo "Function: " . $backtrace[1]['function'];
  }

}

class ChildrenClass extends ParentClass {

   public function some_func() {
        $this->f();
   }
}


$o = new ChildrenClass;
$o->some_func();

And it correctly outputs me:

Class: ChildrenClass
Function: some_func

The question is: is my solution appropriate or there is a better way to achieve this? I tried to use __CLASS__ and __FUNCTION__ but it always gives me a classname and function name of the parent class.

A: 

If you print out the $backtrace var you might see it goes into a more classes

echo "Debug:<pre>".print_r($backtrace,true)."</pre><br />";

So calling

$backtrace[1]['class'] 

will work but you might make this dynamic. Something like:

// Loop, pseudo-code 
$i = 0;
$backtrace[$i]['class']
$i++;
Phill Pafford
+1  A: 

You can also get the name of child class by http://php.net/get_called_class

SeniorDev