PHP Magic Constants Explained

By Avinash

January 27, 2012Tutorial2 Comments

Like PHP Magic Methods we have number of Constants defined in PHP. PHP team has declared 8 of the constants as Magic Constants.

These constants generally starts and ends with __ (double underscore).

These constants provides different values like current file name, current class name, etc. And the value of this constants will change based on where those are used. Lets get into each one.

__LINE__

This will print the line number on which this constant is used. Have a look at the below code block.

echo __LINE__; #Print 1 echo __LINE__; #Print 2 echo __LINE__; #Print 3
 echo __LINE__; #Print 1
echo __LINE__; #Print 2
echo __LINE__; #Print 3

__FILE__

This will print full path to your file name in which this is used. If you have used this constant in included file then it will print the full path to the included file.

__DIR__

This will print full path to directory in which your file is places. Same as __FILE__, if you have used this in include then it will return full path to the included file’s directory.

This constant in introduced in PHP 5.3.

__FUNCTION__

You can use this constant in any function and it will return the name of the function in which that is used. In PHP 4 this constant return the function name always in lowercase but from the newer version of PHP 4 which is PHP 4.3.0 this constant will return function name as it is (case-sensitive).

__CLASS__

This will return the class name in which this is used. In PHP 4 it was returning always in lowercase but from PHP 5 it returns as it is (case-sensitive). PHP 5.4 this case be used in traits also. When used in a trait method, __CLASS__ is the name of the class the trait is used in.

__TRAIT__

This is introduced in PHP 5.4 and it will return the traits name in which this is used.

__METHOD__

This will return name of the class method name and it will return as it is.

__NAMESPACE__

This will return the name of the current namespace (case-sensitive). This constant is added in PHP 5.3.0.

Conclusion

This are the constants that can be useful based on need. But yes this are useful when you really need this values.

Share This Article