How to get the name of the current function?

Asked

Viewed 1,298 times

5

Good evening. I wonder if there’s any way to get the name of the function being used, like this:

public function nome_funcao(){ 

    $nome_funcao = $this -> "nome_funcao";

}

I don’t know if I was clear, but I want to redeem the name of the function within the function I’m using. Is it possible?

1 answer

8


__FUNCTION__

As of version 4.3.0 of PHP there is a magic constant __FUNCTION__ that makes exactly this function:

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

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

The code above returns method. See working on Repl.it or in the Ideone.

__METHOD__

There is still the constant __METHOD__, from version 5.0.0 of PHP, which can be used next to classes and the difference from it to __FUNCTION__ is that __METHOD__ returns the class name as well.

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

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

The exit will be:

Foo::method

Including the class name Foo.

It is interesting to note that when the executed method is inherited from a parent class, the class name returned by __METHOD__ will also be of the parent class, as this is where the method is defined.

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

class Foo extends Bar {}

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

The exit will be Bar::method even if the object is an instance of Foo.

  • That’s right! Thank you

  • 2

    There is the constant __METHOD__ also that it should work if you are using classes. If there is a difference, I cannot say.

  • I just noticed that in the manual you posted. I’m going to run some tests. Hug.

  • 2

    The constant __METHOD__ returns the class name together, this is the difference.

  • Interesting the final example you put. Congratulations and thank you.

  • Hi Anderson. I don’t know if I could fit a question on Sopt about that, because I think the answer is just a yes or no. This method __METHOD__ php would be what is called reflection? for example: $var = __METHOD__;? From now on, thank you.

  • 1

    @Andreicoelho too. Reflection is just the technique of using code to extract information from the code itself. So, yes, it’s reflection. For other situations, you can use the api Reflection of PHP.

  • Interesting. I was researching about it. Thank you Anderson!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.