Advertisement
Google Ad Slot: content-top
PHP Magic Constants
Magic constants are predefined constants that change based on their location in the code. Unlike regular constants, they do not have fixed values; instead, their values change depending on where they are used. Magic constants start and end with double underscores (__), except for the ClassName::class constant.
Summary of PHP Magic Constants
Magic Constant |
Description |
|---|---|
Current line number |
|
Full path and filename of the file |
|
Directory of the file |
|
Function name |
|
Class method name |
|
Current namespace |
|
Trait name (PHP 5.4+) |
|
Returns the name of the specified class and the name of the namespace, if any. |
1. __LINE__
- Represents the current line number in the script.
2. __FILE__
- Represents the full path and filename of the file.
- Useful for finding the script's exact location.
3. __DIR__
- Represents the directory of the file.
4. __FUNCTION__
- Represents the function name (case-sensitive) where it is used.
- If used outside a function, it will return an empty string.
5. __CLASS__
- Represents the class name (case-sensitive) where it is used.
- If used outside a class, it returns an empty string.
- From PHP 5.4 onward,
__CLASS__includes the namespace in its value (if applicable).
6. __METHOD__
- Represents the class method name where it is used.
- Combines the class name and the method name.
7. __NAMESPACE__
- Represents the name of the current namespace.
- If used outside of any namespace, it returns an empty string.
8. __TRAIT__ (Introduced in PHP 5.4)
- Represents the trait name where it is used.
- Useful for traits to refer to themselves.
9. ClassName::class
- Returns the name of the specified class and the name of the namespace, if any.