Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get current function name in PHP?
In PHP, you can get the current function name using magic constants like __FUNCTION__ and __METHOD__. These constants provide different levels of information about the executing function or method.
Using __FUNCTION__ Magic Constant
The __FUNCTION__ constant returns only the function name without class information ?
<?php
class Base {
function display() {
echo "\nBase class function declared final!";
var_dump(__FUNCTION__);
}
function demo() {
echo "\nBase class function!";
}
}
class Derived extends Base {
function demo() {
echo "\nDerived class function!";
}
}
$ob = new Base;
$ob->demo();
$ob->display();
$ob2 = new Derived;
$ob2->demo();
$ob2->display();
?>
Base class function! Base class function declared final!string(7) "display" Derived class function! Base class function declared final!string(7) "display"
Using __METHOD__ Magic Constant
The __METHOD__ constant returns both class name and method name in the format ClassName::methodName ?
<?php
class Base {
function display() {
echo "\nBase class function declared final!";
var_dump(__FUNCTION__);
}
function demo() {
echo "\nBase class function!";
var_dump(__METHOD__);
}
}
class Derived extends Base {
function demo() {
echo "\nDerived class function!";
}
}
$ob = new Base;
$ob->demo();
$ob->display();
$ob2 = new Derived;
$ob2->demo();
$ob2->display();
?>
Base class function!string(10) "Base::demo" Base class function declared final!string(7) "display" Derived class function! Base class function declared final!string(7) "display"
Simple Function Example
For standalone functions (not in classes), both constants work similarly ?
<?php
function myFunction() {
echo "Function name: " . __FUNCTION__ . "<br>";
echo "Method name: " . __METHOD__ . "<br>";
}
myFunction();
?>
Function name: myFunction Method name: myFunction
Comparison
| Magic Constant | Returns | Use Case |
|---|---|---|
__FUNCTION__ |
Function/method name only | When you need just the function name |
__METHOD__ |
Class::method format | When you need class context |
Conclusion
Use __FUNCTION__ for simple function names and __METHOD__ when you need class context. Both constants are compile-time constants that provide valuable debugging and logging information.
Advertisements
