PHP 8.4.1 Released!

魔术常量

有九个魔术常量它们的值随着它们在代码中的位置改变而改变。例如 __LINE__ 的值就依赖于它在脚本中所处的行来决定。这些特殊的常量不区分大小写,如下:

PHP 的魔术常量
名字 说明
__LINE__ 文件中的当前行号。
__FILE__ 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。
__DIR__ 文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录。它等价于 dirname(__FILE__)。除非是根目录,否则目录中名不包括末尾的斜杠。
__FUNCTION__ 当前函数的名称。匿名函数则为 {closure}
__CLASS__ 当前类的名称。类名包括其被声明的作用域(例如 Foo\Bar)。当用在 trait 方法中时,__CLASS__ 是调用 trait 方法的类的名字。
__TRAIT__ Trait 的名字。Trait 名包括其被声明的作用域(例如 Foo\Bar)。
__METHOD__ 类的方法名。
__NAMESPACE__ 当前命名空间的名称。
ClassName::class 完整的类名。

添加备注

用户贡献的备注 3 notes

up
7
Rich
1 year ago
<?php

namespace My\App {
class
Api {
public static
fetch() {
print
__FUNCTION__ . "\n"; // outputs fetch
print __METHOD__ . "\n"; // outputs My\App\Api::fetch
}
}

Api::fetch();
}

namespace {
My\App\Api::fetch();
}
?>

__METHOD__ outputs a fully qualified method name; __FUNCTION__ when used in a method, outputs just the method name.
up
2
chris at ocproducts dot com
1 year ago
Note that __CLASS__ and __METHOD__ both reference the class the code is written in, not whatever the object class is. E.g. if you have an object of class B inheriting from class A, any usage of __CLASS__ in class A is going to give "A".
up
2
theking2 at king dot ma
2 years ago
If PHP is run inside a web server request there is an important difference between the __DIR__ constant and $_SERVER['DOCUMENT_ROOT'].

Where __DIR__ of a PHP script contained within a sub-folder will include the complete server path $_SERVER['DOCUMENT_ROOT'] will contain a server path up to the _root_ of the application. This can be helpful when for instance an auto-loader is defined in an include file sitting inside a sub-folder and where the classes are located in another folder at the root of the application.
To Top