How to get a method name from within a method in PHP?

In PHP, you can get the name of the current method (function) from within the method using the PHP magic constant __METHOD__. Here’s an example:

php
class MyClass {
public function myMethod() {
$methodName = __METHOD__;
echo "The current method is: " . $methodName;
}
}

$obj = new MyClass();
$obj->myMethod(); // outputs "The current method is: MyClass::myMethod"

In the example above, the __METHOD__ constant is used to get the name of the current method within the myMethod() function of the MyClass class. The __METHOD__ constant returns a string that includes the class name and the method name, separated by a double colon.

Note that the __METHOD__ constant only works within a class method. If you want to get the name of the current function in a regular function or outside of any function, you can use the __FUNCTION__ constant instead.

Leave a Reply