PHP Magic Constants
Last Updated on: December 21, 2022
One of the cool and overlooked features of PHP is the presence of “magic constants”.
These predefined constants provide helpful information about the current environment or context in which a script runs.
Here are the nine magic constants currently available in PHP:
- __LINE__ – This constant returns the current line number of the file in which it is used.
- __FILE__ – This constant returns the full path and filename of the file in which it is used.
- __DIR__ – This constant returns the directory of the file in which it is used.
- __FUNCTION__ – This constant returns the function name in which it is used.
- __CLASS__ – This constant returns the class name in which it is used.
- __TRAIT__ – This constant returns the trait name in which it is used.
- __METHOD__ – This constant returns the class method name in which it is used.
- __NAMESPACE__ – This constant returns the current namespace name in which it is used.
- __DEBUGINFO__ – This constant is used to return the debug information for a class.
These magic constants can be handy in a variety of situations. For example, you can use the __LINE__ constant to display the line number of an error message or use the __FILE__ constant to include a file based on its path. You can also use the __CLASS__, __METHOD__, and __FUNCTION__ constants to get information about the current class, method, or function, respectively.
It’s important to note that magic constants are case-sensitive and should always be written in uppercase. They can be used within a script or in a string passed to the PHP function “echo” or “print.”
Give these a try in your next project and see how they can help you to get useful debug info and be more efficient in your code.
Get notified of new posts: