Magic Constants in PHP

Magic constants are the predefined constants in PHP that change depending on where they are used. They start with double underscore (__) and ends with double underscore. Magic constants are case-insensitive. There are eight magical constants in PHP.


__LINE__

The __LINE__ constant represents current line number where it is used.

Example :
<?php
echo "Line number is " . __LINE__;
?>

Output :
Line number is 2


__FILE__

The __FILE__ constant represents full path and file name of the file. If it is used inside an include, name of included file is returned.

Example :
<?php
echo "The full path of this file is: " . __FILE__;
?>

Output :












__DIR__

The __DIR__ constant represents full directory path of the file.
<?php
echo "The directory of this file is: " . __DIR__;
?>

Output :












__FUNCTION__

The __FUNCTION__ constant represents the function name where it is used. If it is used outside of any function, then it will return blank.

Example :
<?php
function myFunction(){
    echo  "The function name is - " . __FUNCTION__;
}
myFunction();
?>

Output :
The function name is - myFunction


__CLASS__

The __CLASS__ constant  represents the class name where it is used. If it is used outside of any function, then it will return blank.

Example :
<?php
class phpClass
{
    public function getClassName(){
        return __CLASS__;
    }
}
$name = new phpClass();
echo $name->getClassName();
?>

Output :
phpClass


__TRAIT__

The __TRAIT__ constant represents the trait name where it is used. If it is used outside of any function, then it will return blank.

Example :
<?php 
trait created_trait{ 
function myfun(){ 
echo __TRAIT__;


class my_ex{ 
use created_trait; 

$a = new my_ex; 
$a->myfun(); 
?>

Output :
created_trait


__METHOD__

The __METHOD__ constant represents the name of the class method where it is used. The method name is returned as it was declared.

Example :
<?php 
class myex
{
    public function methodName(){
        echo __METHOD__;
    }
}
$a = new myex;
$a->methodName();
?>

Output :
myex::methodName


__NAMESPACE__

The __NAMESPACE__ constant represents the name of the current namespace.

Example :
<?php
namespace MyNamespace;
class myClass
{
    public function getNamespace(){
        return __NAMESPACE__;
    }
}
$a = new myClass();
echo $a->getNamespace();
?>

Output :
MyNamespace

0 Comments