Is there a function that can return the name of the current function a program is executing?
Asked
Active
Viewed 4.9k times
2 Answers
191
Yes, you can get the function's name with the magic constant __FUNCTION__
class foo
{
function print_func()
{
echo __FUNCTION__;
}
function print_method()
{
echo __METHOD__;
}
}
$obj = new foo();
$obj->print_func(); // Returns: print_func
$obj->print_method(); // Returns: foo::print_method

Matt Fletcher
- 8,182
- 8
- 41
- 60

Sarfraz
- 377,238
- 77
- 533
- 578
-
2Awesome. Magic constants! I wasn't sure if there were variables for this but there are. This will save me a lot of code, thank you. – Cian E Jan 22 '10 at 08:47
-
Clear example, thanks – Bearwulf Feb 26 '13 at 12:48
-
2+1 for showing the difference between the two magic constants by example and its relevant output. Succinct. – Bhavik Shah Jan 27 '14 at 05:13
17
Maybe via debug_backtrace http://www.php.net/manual/en/function.debug-backtrace.php

robertbasic
- 4,325
- 1
- 27
- 25
-
1
-
24Why did this get so many downvotes, its a valid way of doing it, just not the preferred method. – Cameron Martin Jun 06 '12 at 19:14
-
2Good developing isn't making it work, it's doing it correctly. But I wouldn't downvote, I would simply refrain from upvoting. – SBoss Mar 19 '15 at 10:03
-
1only **`debug_backtrace()`** works correctly, when function is included in other functions too.. – T.Todua Apr 25 '15 at 08:59
-
@SBoss good development isn't doing it "correctly" - that's subjective. Good development is making it work according to a requirement (usually an issue in the issue tracker with details on what's needed to be done). Without knowing what's the task at hand - `debug_backtrace` and `magic constants` are equally "correct". He could be writing a test case and `debug_backtrace` might actually be a better fit for all we know. :) – tftd Oct 28 '21 at 13:35