how do I know the caller of a function in php ?
Asked
Active
Viewed 1,114 times
2
-
possible duplicate of [PHP: friend classes and ungreedy caller function/class](http://stackoverflow.com/questions/2528671/php-friend-classes-and-ungreedy-caller-function-class) and [a couple others](http://stackoverflow.com/search?q=debug_backtrace+php). You should also read through [PHP debug_backtrace in production code?](http://stackoverflow.com/questions/346703/php-debug-backtrace-in-production-code) – Gordon Jul 25 '10 at 20:56
3 Answers
5
Not sure why you would ever care about this, but you can figure that out from the debug_backtrace()
function.

Daniel Egeberg
- 8,359
- 31
- 44
-
2It's fairly common in logging functions, rather than having to pass `__FILE__` and `__LINE__` etc. – MrWhite Jul 25 '10 at 20:52
-
2Yes, and note that there is a moderate performance hit every time you call it. Don't use it in production code... – ircmaxell Jul 25 '10 at 21:28
-
1
-
@Charles I wouldnt use it *inside* error logging functions either. At least not each time. Not every error is so severe that it needs the backtrace. Use debug_backtrace when you need the backtrace to debug, but not to fiddle something like the caller from it. – Gordon Jul 26 '10 at 13:01
4
I'm not sure why you want this, but let me raise a huge red flag - writing code whose behaviour depends on the caller generates very non-modular, hard to debug and downright crazy programs. That said, if you have a valid reason, something like...
function caller()
{
$stackTrace = debug_backtrace();
if (count ($stackTrace) < 1)
return "None";
else if (count ($stackTrace) < 2)
return "Global scope " . $stackTrace[count($stackTrace)]["file"];
else
return $stackTrace[count($stackTrace) - 1]["function"];
}
(This was written off the cuff, so might not be robust in all situations. See http://uk3.php.net/manual/en/function.debug-backtrace.php for more)

Adam Wright
- 48,938
- 12
- 131
- 152
3
how do I know the caller of a function in php ?
Pass it into the callee. That's the most sane approach.

Gordon
- 312,688
- 75
- 539
- 559
-
-
1@typoking with `$this`, `__FUNCTION__`, `__CLASS__`, whatever you need in the callee - just dont do it with `debug_backtrace` unless you need the backtrace. – Gordon Jul 25 '10 at 21:12