__FUNCTION__ 返回「函式/方法名稱」
__METHOD__ 返回「類別名稱::方法名稱」
<?php
class UserService {
public function register($data) {
echo "FUNCTION: " . __FUNCTION__ . "\n"; // register
echo "METHOD: " . __METHOD__ . "\n"; // UserService::register
}
public static function findById($id) {
echo "FUNCTION: " . __FUNCTION__ . "\n"; // findById
echo "METHOD: " . __METHOD__ . "\n"; // UserService::findById
}
}
// 實例方法
$service = new UserService();
$service->register(['name' => 'John']);
// 靜態方法
UserService::findById(123);
// 全域函式 (兩者相同)
function helper() {
echo __FUNCTION__ . " == " . __METHOD__ . "\n"; // helper == helper
}
helper();
| 常數 | 返回值 | 備註 |
|---|---|---|
| __LINE__ | 目前行號 | 整數 |
| __FILE__ | 完整檔案路徑 | 已解析符號連結 |
| __DIR__ | 檔案目錄 | PHP 5.3+,等同 dirname(__FILE__) |
| __FUNCTION__ | 函式/方法名 | 區分大小寫,PHP 5+ |
| __CLASS__ | 類別名稱 (含命名空間) | 區分大小寫,PHP 5+ |
| __TRAIT__ | Trait 名稱 (含命名空間) | PHP 5.4+ |
| __METHOD__ | 類別::方法名 | 區分大小寫,PHP 5+ |
| __NAMESPACE__ | 目前命名空間 | PHP 5.3+,編譯期常數 |
function logInfo($message, array $context = []) {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1] ?? [];
$location = ($trace['class'] ?? '') . '::' . ($trace['function'] ?? 'global');
$log = [
'time' => date('c'),
'level' => 'info',
'location' => $location, // 自動包含類別::方法
'message' => $message,
'context' => $context
];
error_log(json_encode($log, JSON_UNESCAPED_UNICODE));
}
// 使用
class OrderController {
public function create() {
logInfo('建立訂單', ['user_id' => 123]);
// 自動記錄: OrderController::create
}
}
class Dispatcher {
public function dispatch($controllerClass, $method) {
$fullMethod = "{$controllerClass}::{$method}";
// 驗證方法存在
if (!method_exists($controllerClass, $method)) {
throw new NotFoundException("Method {$fullMethod} not found");
}
// 記錄分派資訊 (可用於審計、效能監控)
$start = microtime(true);
$result = (new $controllerClass)->$method();
$duration = microtime(true) - $start;
metrics()->timing('dispatch.duration', $duration, ['method' => $fullMethod]);
return $result;
}
}
class TestCase extends PHPUnit\Framework\TestCase {
public function setUp(): void {
$this->testName = __METHOD__; // 取得完整測試方法名
}
public function testUserRegistration() {
// 測試邏輯...
}
}