PHP Magic Constants
PHP provides a large number of predefined constants to any script which it runs. There are nine magical constants that change depending on where they are used.
1. File and Directory
__FILE__: The full path and filename of the file. 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 todirname(__FILE__).
echo "File: " . __FILE__;
echo "Directory: " . __DIR__;
2. Code Structure
__LINE__: The current line number of the file.__FUNCTION__: The function name.__CLASS__: The class name. The class name includes the namespace it was declared in (e.g.Foo\Bar).__METHOD__: The class method name.__NAMESPACE__: The name of the current namespace.__TRAIT__: The trait name. The trait name includes the namespace it was declared in.
namespace MyProject;
class MyClass {
public function myMethod() {
echo __METHOD__; // Outputs: MyProject\MyClass::myMethod
}
}
3. ClassName::class
Although not strictly a magic constant starting with __, the ::class keyword is a special constant that returns the fully qualified name of a class.
namespace MyProject;
class User {}
echo User::class; // Outputs: MyProject\User