PHP
语言参考 | Language Reference

Magic constants

Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are nine magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. All these "magical" constants are resolved at compile time, unlike regular constants thats resolved at runtime. These special constants are case-insensitive and are as follows:

NameDescription
__LINE__The current line number of the file.
__FILE__The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__The function name.
__CLASS__The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__The class method name.
__NAMESPACE__The name of the current namespace.
ClassName::classThe fully qualified class name. See also ::class.

See also get_class(), get_object_vars(), file_exists() and function_exists().

Changelog

VersionDescription
5.5.0Added ::class magic constant
5.4.0Added __TRAIT__ constant
5.3.0Added __DIR__ and __NAMESPACE__ constants
5.0.0Added __METHOD__ constant
5.0.0Before this version values of some magic constants were always lowercased. All of them are case-sensitive now (contain names as they were declared).
4.3.0Added __FUNCTION__ and __CLASS__ constants
4.0.2__FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances

← Syntax

Expressions →

© 1997–2017 The PHP Documentation Group

Licensed under the Creative Commons Attribution License v3.0 or later.

https://secure.php.net/manual/en/language.constants.predefined.php