82

Is there a function that can return the name of the current function a program is executing?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cian E
  • 1,079
  • 1
  • 8
  • 9

2 Answers2

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
17

Maybe via debug_backtrace http://www.php.net/manual/en/function.debug-backtrace.php

robertbasic
  • 4,325
  • 1
  • 27
  • 25
  • 1
    -1 - magic constants are proper way to do this. – Crozin Jan 22 '10 at 09:37
  • 24
    Why 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
  • 2
    Good 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
  • 1
    only **`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