Skip to main content

PHP Magic Constants

By SamK
0
0 recommends
Category(s)
Topic(s)

PHP features nine predefined constants known as "magic constants" because their values vary depending on where they are used.

These magic constants are denoted by a double underscore at the beginning and end, with the exception of the ClassName::class constant.

Magic Constants

Below are the magic constants along with description and examples:

__CLASS__: If used inside a class, the class name is returned.

<?php
class Car {
    public function getClassName() {
        return __CLASS__;
    }
}

$audi = new Car();
echo $audi->getClassName();
?>

/*
Output:
Car
*/

__DIR__: The directory of the current file is returned.

<?php
echo __DIR__;
?>

/*
Output:
C:/phpscripts/test-scripts
*/

__FILE__: The current file name including the full path is returned.

<?php
echo __FILE__;
?>

/*
Output:
C:/phpscripts/test-scripts/file.php
*/

 __FUNCTION__:  If used inside a function, the function name is returned.

<?php
function getFunctionName() {
    return __FUNCTION__;
}

echo getFunctionName();
?>

/*
Output:
getFunctionName
*/

__LINE__: The current line number is returned. 

<?php
echo __LINE__;
?>

/*
Output:
2
*/

__METHOD__: If used inside a function that belongs to a class, both class and function name are returned.    

<?php
class Car {
    public function getMethodName() {
        return __METHOD__;
    }
}

$honda = new Car();
echo $honda->getMethodName();
?>

/*
Output:
Car::getMethodName
*/

__NAMESPACE__:  If used inside a namespace, the name of the namespace is returned.

<?php
namespace MyNamespace;

function getNamespaceName() {
    return __NAMESPACE__;
}

echo getNamespaceName();
?>

/*
Output:
MyNamespace
*/

__TRAIT__: If used inside a trait, the trait name is returned.

<?php
trait MessageTrait {
    public function displayTraitName() {
        echo __TRAIT__;
    }
}

class Greeting {
    use MessageTrait;
}

$instance = new Greeting();
$instance->displayTraitName();
?>

/*
Output:
MessageTrait
*/

ClassName::class: Returns the name of the specified class and the name of the namespace, if any.

<?php
namespace MyNamespace;

class Car {
    public function getClassName() {
        return self::class;
    }
}

$Mersadise = new Car();
echo $Mersadise->getClassName();
?>

/*
Output:
MyNamespace\Car
*/

Questions & Answers