Can you get a method name from within a method in PHP?

Viewed 73041

Is it possible to do something like this?

public function something() {
    $thisMethodName = method_get_name(); 
}

Where method_get_name() returns the method's name?

8 Answers

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:

protected static function getUserResponseByAccessTokenRequestOptions(string $myParam): array
{
    return array_merge(parent::{__FUNCTION__}($myParam), [
        'myValue' => '123'
    ]);
}

instead of this:

protected static function getUserResponseByAccessTokenRequestOptions(string $myParam): array
{
    return array_merge(parent::getUserResponseByAccessTokenRequestOptions($myParam), [
        'myValue' => '123'
    ]);
}

And does not care about replacing the name of the method inside method if I want to change it.

Perhaps missing late bindings in this way.

when class B extend class A:

__METHOD__ always return the "className::" part referred to A (A::methodName)

Solution is:

static::class."::".__FUNCTION__

In this way you obtain the class reference to current working class (B::methodName)

Related