Introduction
A constant is a name or an identifier for simple values. A constant value cannot change during the execution of the script. By default a constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.
To define a constant you have to use the define() function and to retrieve the value of a constant, you have to simply specify its name. Unlike with variables, you do not need to have a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically.
Magic constant in PHP
PHP provides a large number of predefined constants for any script. There are five magical constants that change depending on where they are used. For example, the value of __FILE__ depends on the file that it's used in. These special constants are case-insensitive. There are many magical constants available in PHP, but seven magical constants are most important. The most useful magic constants are five, like _LINE_, _DIR_, _FILE_ etc. These constants are case-sensitive. Use of the magic constants are as follows.
- __LINE__: Indicate current line number of the file.
- __FILE__: This constant is used to indicate the current directory in which the file is present.
- __FUNCTION__: This constant is used to indicates the path of the file.
- __CLASS__: This constant Returns the class name.
- __METHOD__: Returns the function name.
- __DIR__: This constant is used to indicate the current directory in which the file is present.
- __NAMESPACE__: Displays the namespace in which we are working.
Example
<?php
function fun_magic(){
echo __LINE__."<BR/>";
echo __FILE__."<BR/>";
echo __DIR__."<BR/>";
ECHO __FUNCTION__."<BR/>";
ECHO __METHOD__."<BR/>";
ECHO __NAMESPACE__."<BR/>";
}
fun_magic();
?>
Output