How do I get the name of the current function?

5

Good evening. I would like to know if there is any way to get the name of the function being used, type this:

public function nome_funcao(){ 

    $nome_funcao = $this -> "nome_funcao";

}

I do not know if it was clear, but I want to retrieve the function name inside the function I'm using. Is it possible?

    
asked by anonymous 09.04.2017 / 03:39

1 answer

8

__FUNCTION__

Starting with version 4.3.0 of PHP there is the magic constant % with% does exactly this function:

class Foo {
    public function method()
    {
        echo __FUNCTION__ ;
    }
}

$f = new Foo();
$f->method();

The above code returns __FUNCTION__ . See working at Repl.it or Ideone >.

method

There is still the constant __METHOD__ , starting with version 5.0.0 of PHP, which can be used next to classes and the difference of it to __METHOD__ is that __FUNCTION__ returns the name of the class too. p>

class Foo {
    public function method()
    {
        echo __METHOD__ ;
    }
}

$f = new Foo();
$f->method();

The output will be:

Foo::method

Including the class name __METHOD__ .

It is interesting to note that when the executed method is inherited from a parent class, the class name returned by Foo will also be from the parent class, since it is where the method is defined.

class Bar
{
  public function method()
  {
    echo __METHOD__;
  }
}

class Foo extends Bar {}

$foo = new Foo();
$foo->method();

The output will be __METHOD__ even if the object is an instance of Bar::method .

    
09.04.2017 / 04:09