PHP Magic Constants are some predefined constants you can say, which provide some special features to the PHP language. These can be used by embedding with
echo(), and each of these provide a special kind of information which a programmer may need.
These are called Magic Constant because unlike regular constants Magic Constants doesn,t always give the same value,i.e., they would have different values for different scenarios. For example, a Magic Constant which returns the line number on which it has been used, will give different values for different lines.
These Magic Constants are case-insensitive, so no problem with any case. Always remember that Magic Constants starts and end with double underscore
(__). Now below are given some Magic Constants with proper explanation and examples, it will help you to understand it very easily. Please continue reading.
__LINE__ magic constant
returns the line number on which it has been used. For example, if you use it on first line it will return 1, on 3rd line it will return 3 and so on. Take a look at the example below to understand how you can use it with echo().
__FILE__ magic constant
returns the exact path of the file in which it is used in combination with echo() but if you use it with include() then it will return the filename of the file which is included. Take a look at the example below to understand it properly.
__FUNCTION__ magic constant
returns the name of the function inside which it is been used. It is a case sensitive constant so it will return the function name in the exact case in which it is written. Earlier in PHP 4, it used to return the function name in lowercase which was later changed in PHP 5.
__CLASS__ magic constant works same as
it returns class name. It is also case sensitive so it will return the name of the class in the exact same case in which it was declared. See the example.
__METHOD__ magic constant
return the name of the method inside which it has been used. It is also case sensitive so it will return the name same as it was declared.
__DIR__ magic constant
returns the directory of the file. If used inside an include, the directory of the included file is returned.
__NAMESPACE__ magic constant
returns the name of the current namespace.
__trait__ magic constant
return the trait name where this magic constant is included. Take a look at the example below to understand how it work.