Is it possible to do something like this?
public function something() {
$thisMethodName = method_get_name();
}
Where method_get_name()
returns the method's name?
Is it possible to do something like this?
public function something() {
$thisMethodName = method_get_name();
}
Where method_get_name()
returns the method's name?
As smartj suggested you can try the magic constant
__METHOD__
, but remember that this will return a string containing also your class name, i.e. 'MyClass::something'. Using__FUNCTION__
instead will return 'something'.With
__FUNCTION__
i can use this:instead of this:
And does not care about replacing the name of the method inside method if I want to change it.
While you can use the magic constant
__METHOD__
I would highly recommend checking out PHP's reflection. This is supported in PHP5.You can then do kick-ass stuff like inspect the signature, etc.
Hackish, but you could also probably dig it out of the debug_backtrace() return value.
Using
__FUNCTION__
is the way to go instead of:which is flawed in several ways adding a variable and memory to store the method name as a string and duplicating what already exists, thus unnecessarily adding resources used, (if you do this for a large library with many methods, it matters greatly).
Magic constants in PHP are guaranteed not to change, while this approach would require applicable editing if the method name were changed, thus introducing the potential for an inconsistency (note, I did say potentially, meaning simply it is an otherwise unnecessary edit if the magic constant were used instead).
The time and effort to name a variable, re-type the method name as a string assigned to that unnecessary variable and of course properly referencing the variable name, which is the motivation for PHP supplying magic constants to begin with (and refuting any claim
__FUNCTION__
is unnecessary).Sure, you want the magic constants.
Find out more from the php manual