This article demonstrates how to print the name of the current function being executed in PHP.

1. Using Magic Constants

You can use the predefined magic constant __FUNCTION__ to get the name of the function. It is resolved at compile time and is case-insensitive. The following program uses it to print the name of a member function of a class.

Download  Run Code

 
If you want to return the class name along with the function name, consider using the __METHOD__ magic constant:

Download  Run Code

 
You can also use the __FUNCTION__ or __METHOD__ magic constants to print the names of normal functions as well:

Download  Run Code

2. Using debug_backtrace() function

Another option to get the name of the calling function is using the debug_backtrace() function. It generates the PHP backtrace and returns an array of associative arrays containing information like the current function name, current line number, current file name, current class name, current object, current call type, etc. Here’s how you can get the current function name from the returned elements of debug_backtrace().

Download  Run Code

 
It should be noted that debug_backtrace() is a resource-intensive function. If you just need to find the current function name, it is better to stick to the __FUNCTION__ or __METHOD__ magic constants.

That’s all there is to printing the name of the current function being executed in PHP.