Page 1 of 1
How to find method name that called currently ex. method
Posted: Wed Jan 21, 2009 12:29 pm
by atonyman
Ok. So I am trying to figure out how to track down the name of the method that called the currently executing method. I've checked FAQs and RTFM etc. Any help greatly appreciated. FYI: I need this for error reporting in an Adapter Pattern db integration class.
Code: Select all
class TestClass {
function __construct(){
$this->doSomething();
}
function doSomething(){
// Don't know what to put here but I want the value to be '__construct'
echo "Name of method that called this method is".$SomebodysAnswerHere;
}
}
Cheers,
atonyman
Re: How to find method name that called currently ex. method
Posted: Wed Jan 21, 2009 12:41 pm
by msurabbott
I wish I had a response for you but I have actually been looking for this myself for about 2 years..
Re: How to find method name that called currently ex. method
Posted: Wed Jan 21, 2009 12:46 pm
by Burrito
I don't think it's available in php like it is in perl (caller.)
Re: How to find method name that called currently ex. method
Posted: Wed Jan 21, 2009 1:40 pm
by pickle
debug_backtrace()
I use it for pretty much this exact purpose for my
dump_array() function. Where the function references ['file'] and ['line'], you can also reference ['function']
Re: How to find method name that called currently ex. method
Posted: Wed Jan 21, 2009 1:46 pm
by VladSun
Awesome, pickle
I also found the __METHOD__ magic constant (PHP 5.0+)

In fact it will contain both class name and method called in this format:
class::method
More interesting PHP magics:
http://php.net/manual/en/language.const ... efined.php
Re: How to find method name that called currently ex. method
Posted: Wed Jan 21, 2009 3:11 pm
by atonyman
Thanks to everyone's quick replies.

I have implemented the debug_backtrace for my solution. Since I only wanted the 'calling' class/method I used the second element of the debug_backtrace array (actually [1]).
Here's what my solution looks like in sample code:
Code: Select all
class Test {
function __construct(){
$this->doSomething();
}
function doSomething(){
$dbt = debug_backtrace();
echo "Here is the name of the object and method that called this method :".$dbt[1]['class']." ".$dbt[1]['function'];
}
}
$test = new Test;
The above outputs the following: Here is the name of the object and method that called this method :Test __construct