251
votes

Is it possible?

function test()
{
  echo "function name is test";
}
4
Just out of curiosity, when is there a need for this? Is it possible to create functions that you don't know the name of?DisgruntledGoat
One possible use would be logging your execution. If you're writing "I had an error in " . FUNCTION to a logfile or something. This way, if the function name is changed you don't have to worry about the person remembering to change the log message.Brian Ramsay
Needed this for logging! thanks for asking :)Rick Kukiela
Also useful if you want to use the function name inside the function (for another use). Like to construct links based on the function, etc. (eg: function name1() then use name1 again inside), would save lots of time if you have the same template for lots of functions.Mafia
@DisgruntledGoat: it is useful if you create functions manually and do not want to edit error message for every function. Adding it into error message means you have less work.John Boe

4 Answers

421
votes

The accurate way is to use the __FUNCTION__ predefined magic constant.

Example:

class Test {
    function MethodA(){
        echo __FUNCTION__;
    }
}

Result: MethodA.

104
votes

You can use the magic constants __METHOD__ (includes the class name) or __FUNCTION__ (just function name) depending on if it's a method or a function... =)

17
votes

If you are using PHP 5 you can try this:

function a() {
    $trace = debug_backtrace();
    echo $trace[0]["function"];
}
1
votes
<?php

  class Test {
     function MethodA(){
         echo __FUNCTION__ ;
     }
 }
 $test = new Test;
 echo $test->MethodA();
?>

Result: "MethodA";