In PHP, magic constants are pre-defined, and used according to its value. These values cannot be changed, can only be used.
Magic constants starts with double underscore and ends with double underscore and in between magic constant name in capital. Magic constants are case-insensitive.
PHP provides 9 different types of magic constants.
Magic constants | Use |
---|---|
__CLASS__ | Returns class name. |
__DIR__ | Returns directory name. |
__FILE__ | Returns file name. |
__FUNCTION__ | Returns function name. |
__LINE__ | Returns line name. |
__METHOD__ | Returns method name with its class name. |
__NAMESPACE__ | Returns namespace name. |
__TRAIT__ | Returns trait name. |
ClassName::class | Returns specified class name and namespace. |
__CLASS__
<?php
class YourShala
{
public function myClassName(){
return __CLASS__;
}
}
$x= new YourShala();
echo $x->myClassName();
?>
__DIR__
<?php
echo "Current directory: " . __DIR__ ;
?>
__FILE__
<?php
?>
__FUNCTION__
<?php
function myTestFunction(){
echo __FUNCTION__;
}
myTestFunction();
?>
__LINE__
<?php
echo "Line number is: " . __LINE__;
?>
__METHOD__
<?php
class YourShala
{
public function myMethodName(){
return __METHOD__;
}
}
$x= new YourShala();
echo $x->myMethodName();
?>
__NAMESPACE__
<?php
namespace YourShala;
class Car
{
public function myNameSpace(){
return __NAMESPACE__;
}
}
$x= new Car();
echo $x->myNameSpace();
?>
__TRAIT__
<?php
trait Company{
function companyName(){
echo __trait__;
}
}
class Car
{
use Company; // trait is used
}
$x= new Car();
echo $x->companyName();
?>
ClassName::class
<?php
namespace YourShala;
class Car
{
echo Car::class; //Classname::class
}
?>