Mar. 13 2011

Get parent function using debug_backtrace()

Sometimes, you need to know the name of the function that called the function you’re currently in. In my case, it’s a logging method in a class. PHP has the magical constant __FUNCTION__ that gives you the name of the current function, but nothing to get the calling function.

You can use debug_backtrace() to get that calling function:

$arr = debug_backtrace();
$func = $arr[1]['function'];

Pretty simple stuff! debug_backtrace() is the same thing as a stack trace that you see in debug consoles of frameworks like Symfony. It’s typically the last 10 or so steps on how you arrived to where you are and includes data like line and file name for easy debugging.

It returns an array of arrays of the steps, starting with where you are (the 0 element) and going back from there. The nested arrays includes the step’s information as elements: function, line of the file, file, class, current object (be careful: the actual object is there), call type (:: for static, -> for methods, and nothing for function), and function args.

1 comment

  1. kenorb
    May 23, 2014 at 5:13 am

    $func = next(debug_backtrace())[‘function’];

Leave a Reply

Previous post:

Next post: interface from fmTuner (modified by me).

Twitter interface from HL Twitter.

Dedicated to my mom, Sharon. May she rest peacefully.
Love you always. (March 23, 1965 - November 12, 2011)

Unsupported Browser!

My site is designed for and currently displays best with modern browsers (and it looks like you don't have one!).

Everything should still function properly, but you won't be able to see all the fancy effects, text, or the way I intended my design to look.

Consider trying the latest version of either Firefox or Chrome... I think you'll like it!

Logan Bibby

P.S.: You can continue viewing my site by clicking the "close" link and you'll never see this again. :)