Print current function name in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php class Example { function foo() { echo "Current function is " . __FUNCTION__, PHP_EOL; } } $obj = new Example(); $obj->foo(); /* Output: Current function is foo */ ?> |
If you want to return the class name along with the function name, consider using the __METHOD__ magic constant:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php class Example { function foo() { echo "Current function is " . __METHOD__, PHP_EOL; } } $obj = new Example(); $obj->foo(); /* Output: Current function is Example::foo */ ?> |
You can also use the __FUNCTION__ or __METHOD__ magic constants to print the names of normal functions as well:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php function foo() { echo "Current function is " . __FUNCTION__, PHP_EOL; } function bar() { echo "Current function is " . __METHOD__, PHP_EOL; } foo(); bar(); /* Output: Current function is foo Current function is bar */ ?> |
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().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php function foo() { $trace = debug_backtrace(); echo "Current function is " . $trace[0]["function"], PHP_EOL; echo "Current line number is " . $trace[0]["line"], PHP_EOL; echo "Current file is " . $trace[0]["file"], PHP_EOL; } foo(); /* Sample Output: Current function is foo Current line number is 10 Current file is /box/script.php */ ?> |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)