PHP में currently executing function/method का नाम प्राप्त करने के magic constants।
Magic Constants
| Constant | Returns | Scope |
|---|---|---|
__FUNCTION__ | Function name (case-sensitive) | Function के अंदर |
__METHOD__ | Class::method name | Method के अंदर |
__CLASS__ | Class name | Class के अंदर |
__TRAIT__ | Trait name | Trait के अंदर |
__NAMESPACE__ | Namespace name | Namespace में |
Basic Usage
<?php
function myFunction() {
echo __FUNCTION__; // myFunction
}
class MyClass {
public function myMethod() {
echo __METHOD__; // MyClass::myMethod
echo __FUNCTION__; // myMethod (only method name)
}
public static function staticMethod() {
echo __METHOD__; // MyClass::staticMethod
}
}
myFunction();
$obj = new MyClass();
$obj->myMethod();
MyClass::staticMethod();
Inheritance के साथ व्यवहार
<?php
class Base {
public function display() {
echo "__FUNCTION__: " . __FUNCTION__ . "\n"; // display
echo "__METHOD__: " . __METHOD__ . "\n"; // Base::display
echo "__CLASS__: " . __CLASS__ . "\n"; // Base
}
}
class Derived extends Base {
public function display() {
echo "__FUNCTION__: " . __FUNCTION__ . "\n"; // display
echo "__METHOD__: " . __METHOD__ . "\n"; // Derived::display (actual called class!)
echo "__CLASS__: " . __CLASS__ . "\n"; // Derived
}
}
$base = new Base();
$base->display();
echo "---\n";
$derived = new Derived();
$derived->display();
Anonymous Functions / Closures
<?php
$closure = function() {
echo __FUNCTION__; // {closure}
};
$arrowFn = fn() => __FUNCTION__; // {closure}
$closure();
$arrowFn();
Trait में
<?php
trait Logger {
public function log($msg) {
echo "[" . __TRAIT__ . "::" . __FUNCTION__ . "] $msg\n";
}
}
class Service {
use Logger;
}
$svc = new Service();
$svc->log('Starting...'); // [Logger::log] Starting...
Debug Backtrace (Caller Info)
<?php
function getCallerInfo() {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
// [0] = getCallerInfo, [1] = caller
if (isset($trace[1])) {
$caller = $trace[1];
return [
'function' => $caller['function'] ?? 'unknown',
'class' => $caller['class'] ?? null,
'file' => $caller['file'] ?? 'unknown',
'line' => $caller['line'] ?? 0,
];
}
return null;
}
function outer() {
inner();
}
function inner() {
$info = getCallerInfo();
print_r($info);
// Array ( [function] => outer [class] => [file] => ... [line] => ... )
}
outer();
Practical: Logging Helper
<?php
function debugLog($message, $context = []) {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$caller = $trace[1] ?? [];
$log = [
'time' => date('c'),
'function' => $caller['function'] ?? 'global',
'class' => $caller['class'] ?? '',
'file' => basename($caller['file'] ?? ''),
'line' => $caller['line'] ?? 0,
'message' => $message,
'context' => $context
];
error_log(json_encode($log, JSON_UNESCAPED_UNICODE));
}
// उपयोग
class UserService {
public function createUser($data) {
debugLog('Creating user', ['email' => $data['email']]);
// ...
}
}