how do I know the caller of a function in php ?
+5
A:
Not sure why you would ever care about this, but you can figure that out from the debug_backtrace() function.
Daniel Egeberg
2010-07-25 20:48:29
It's fairly common in logging functions, rather than having to pass `__FILE__` and `__LINE__` etc.
w3d
2010-07-25 20:52:45
@w3d Good point. Didn't think of that.
Daniel Egeberg
2010-07-25 20:54:06
@w3d it's a fairly common code smell.
Gordon
2010-07-25 21:02:04
Yes, and note that there is a moderate performance hit every time you call it. Don't use it in production code...
ircmaxell
2010-07-25 21:28:50
Don't use it in production code *outside* of error logging functions.
Charles
2010-07-25 22:10:11
Yup, thanks for the clarification @Charles...
ircmaxell
2010-07-25 23:13:27
@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
2010-07-26 13:01:57
+1
A:
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
2010-07-25 20:51:47
+2
A:
how do I know the caller of a function in php ?
Pass it into the callee. That's the most sane approach.
Gordon
2010-07-25 21:07:54