__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
– Andrei Coelho
There is the constant
__METHOD__
also that it should work if you are using classes. If there is a difference, I cannot say.– Woss
I just noticed that in the manual you posted. I’m going to run some tests. Hug.
– Andrei Coelho
The constant
__METHOD__
returns the class name together, this is the difference.– Woss
Interesting the final example you put. Congratulations and thank you.
– Andrei Coelho
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.– Andrei Coelho
@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.– Woss
Interesting. I was researching about it. Thank you Anderson!
– Andrei Coelho