PHP Magic Constants

last edited on: 10-Feb-2018; tagged: php


PHP provides a large number of predefined constants. From this there are nine constants those are called Magic constants. These constants are changed their values depending on where they are used.

 
__LINE__
The __LINE__ constant returns the current line number of the PHP script. Example:

<?php
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 2
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 3
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 4
?> 

__FILE__
The __FILE__ constant returns full the path and name of the PHP that is being executed. If used inside an include(include is a function which is used to include a file in current script) then the name of the included file is returned. Example:

<?php
// Displays the absolute path of this file
echo "The full path of this file is: " . __FILE__;
?>

__DIR__
The __DIR__ constant returns the directory of the file. If used inside an include then the directory of the included file is returned. Example:

<?php
// Displays like: The directory of this file is: C:\xampp\htdocs\testing
echo "The directory of this file is: " . __DIR__;
?>

__FUNCTION__
The __FUNCTION__ constant returns the name of the current function. Example:

<?php
function myFunction()
{
    echo  "The name of the function is: " . __FUNCTION__;
}
myFunction(); // Displays: The name of the function is: myFunction
?>

__CLASS__
The __CLASS__ constant returns the name of the current class. Example:

<?php
class MySampleClass
{
    public function getClassName()
    {
        return __CLASS__;
    }
}
$objMySampleClass = new MySampleClass();
echo $objMySampleClass ->getClassName(); // Displays: MySampleClass
?>

__METHOD__
The __METHOD__ constant returns the name of the current class method. Example:

<?php
class MySampleClass
{
    public function myMethod1(){
        echo __METHOD__;
    }
    public function myMethod2(){
        echo __METHOD__;
    }
}
$objMySampleClass = new MySampleClass();
$objMySampleClass->myMethod1(); // Displays: MySampleClass::myMethod1
echo "<br/>";
$objMySampleClass->myMethod2(); // Displays: MySampleClass::myMethod2
?> 

__NAMESPACE__
The __NAMESPACE__ constant returns the name of the current namespace. Example:

<?php
namespace MyNamespace;
class MySampleClass
{
    public function getNamespace(){
        return __NAMESPACE__;
    }
}
$objMySampleClass = new MySampleClass();
echo $objMySampleClass->getNamespace(); // Displays: MyNamespace
?>
 

Related

PHP Sessions

tagged: php,sessions

PHP Cookies

tagged: php,cookies