tags:

views:

93

answers:

3

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
It's fairly common in logging functions, rather than having to pass `__FILE__` and `__LINE__` etc.
w3d
@w3d Good point. Didn't think of that.
Daniel Egeberg
@w3d it's a fairly common code smell.
Gordon
Yes, and note that there is a moderate performance hit every time you call it. Don't use it in production code...
ircmaxell
Don't use it in production code *outside* of error logging functions.
Charles
Yup, thanks for the clarification @Charles...
ircmaxell
@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
+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
+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
Do you mean with `(this)` or something of the sort?
typoknig
@typoking with `$this`, `__FUNCTION__`, `__CLASS__`, whatever you need in the callee - just dont do it with `debug_backtrace` unless you need the backtrace.
Gordon