PHP provides a large number of predefined constants to any script which it runs. Magic constants have a funny syntax, placing two underscores before and after the constant’s word representation. There are nine magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it’s used on in your script. These special constants are case-insensitive.
A few “magical” PHP constants ate given below:
Name |
Description |
__LINE__ |
Represents current line number where it is used. |
__FILE__ |
The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned. |
__DIR__ |
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. |
__FUNCTION__ |
The function name. |
__CLASS__ |
The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in. |
__TRAIT__ |
The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar). |
__METHOD__ |
The class method name. |
__NAMESPACE__ |
Represents the name of the current namespace. |
ClassName::class |
The fully qualified class name. |
Example of magical constants __LINE__ ,__FILE__ and __DIR__
<?php
echo "Line number " . __LINE__ ."
"; // Displays: Line number 2
echo "Line number " . __LINE__ ."
"; // Displays: Line number 3
// Displays the absolute path of this file
echo "The full path of this file is: " . __FILE__;
// Displays the directory of this file
echo "The directory of this file is: " . __DIR__;
?>
Example of magical constants __FUNCTION__, __METHOD__ , __CLASS__ and __NAMESPACE__
namespace MyNamespace;
class PrintFunMethod
{
function print_func()
{
echo __FUNCTION__;
}
function print_method()
{
echo __METHOD__;
}
function getClassName(){
return __CLASS__;
}
function getNamespace(){
return __NAMESPACE__;
}
}
$obj=new PrintFunMethod();
$obj->print_func();
output will be ---- print_func()
$obj->print_method();
output will be ----- trick::print_method
echo $obj->getClassName(); // Displays: PrintFunMethod
echo $obj->getNamespace(); // Displays: MyNamespace