PHP 魔术常量

Eight interpreter-filled constants and how to use them in debugging and logging.

Beginner
Key PointsA magic constant's value depends on where it sits, changing as code moves.

The eight constants

ConstantValue
__LINE__当前行号
__FILE__文件的完整路径与文件名
__DIR__文件所在目录
__FUNCTION__当前函数名
__CLASS__当前类名(含命名空间)
__METHOD__当前方法名(含类名)
__NAMESPACE__当前命名空间
__TRAIT__当前 trait 名

Line and file

PHP
<?php
echo "第一行代码在第 " . __LINE__ . " 行\n";
echo "这一行在第 " . __LINE__ . " 行\n";

echo basename(__FILE__) . "\n";
echo basename(__DIR__) . "\n";
Output
第一行代码在第 2 行
这一行在第 3 行
magic.php
demo

The file is /var/www/demo/magic.php. __FILE__ yields the absolute path; basename() trims it. Logging absolute paths leaks server layout in production.

Function and class

PHP
<?php
namespace App\Demo;

function show(): void {
    echo __FUNCTION__ . "\n";
    echo __NAMESPACE__ . "\n";
}

class Report
{
    public function run(): void {
        echo __CLASS__ . "\n";
        echo __METHOD__ . "\n";
    }
}

show();
(new Report())->run();
Output
App\Demo\show
App\Demo
App\Demo\Report
App\Demo\Report::run
__FUNCTION__ includes the namespace, __METHOD__ includes the class. For the short name use basename(str_replace('\\', '/', __CLASS__)).

Practical use in logging

To log the caller's line you cannot use __LINE__ inside the function — it always points at the function body. Pass __LINE__ from the call site.

PHP
<?php
function debug(string $msg, int $line = 0): void {
    printf("[%s:%d] %s\n", basename(__FILE__), $line, $msg);
}

debug("开始处理", __LINE__);          // 第 6 行

$total = 0;
for ($i = 1; $i <= 3; $i++) {
    $total += $i;
}
debug("合计 $total", __LINE__);       // 第 12 行
Output
[magic.php:6] 开始处理
[magic.php:12] 合计 6

The debug($msg, __LINE__) idiom is common in Laravel and Symfony logging wrappers. Add a __FILE__ parameter if needed — but avoid absolute paths in production logs.

__DIR__ and includes

__DIR__ locates files independently of the working directory. include "config.php" depends on include_path and CWD; include __DIR__ . "/config.php" does not.

PHP
<?php
// 反例:受工作目录影响
// include "config.php";

// 正例:始终相对本文件
$path = __DIR__ . "/config.php";
echo $path === realpath(__DIR__) . DIRECTORY_SEPARATOR . "config.php" ? "路径正确" : "路径错误", "\n";
echo basename(dirname(__DIR__)), "\n";
Output
路径正确
www

With the file at /var/www/demo/magic.php, dirname(__DIR__) is /var/www. PSR-4 autoloaders locate vendor/autoload.php the same way.

Friends & Partners