PHP Magic Constants

PHP provides a set of predefined constants known as “magic constants.” These constants can change their value dynamically based on the context in which they are used. Magic constants are always written with double underscores both at the beginning and the end of their name (except for ClassName::class).

Tutorials dojo strip



The List of Magic Constants and Their Descriptions

ConstantDescription
__CLASS__Outputs the name of the class when used inside a class.
__DIR__Represents the directory path of the current file.
__FILE__Contains the file name including its complete path.
__FUNCTION__Displays the name of the function, if used within one.
__LINE__Indicates the line number where it is called.
__METHOD__Returns the name of the method along with its class.
__NAMESPACE__Displays the namespace name, if used inside a namespace.
__TRAIT__Reflects the name of the trait, if used inside a trait.
ClassName::classOutputs the name of the class, including the namespace, if applicable.




Examples of PHP Magic Constants in Action

Below, we’ll explore examples of how to utilize these magic constants. For added flavor, the variables and identifiers in the examples are inspired by motorcycle and car brands.

  1. Using __CLASS__
class Ducati {
    public function getClassName() {
        return __CLASS__;
    }
}

$motorbike = new Ducati();
echo $motorbike->getClassName(); // Output: Ducati

  1. Using __DIR__
echo "The directory is: " . __DIR__; 
// Output: Displays the directory path of the current file

  1. Using __FILE__
echo "The file path is: " . __FILE__; 
// Output: Displays the full path and file name

  1. Using __FUNCTION__
function harleyFunction() {
    return __FUNCTION__;
}

echo harleyFunction(); // Output: harleyFunction

  1. Using __LINE__
echo "This is line number: " . __LINE__; 
// Output: Displays the current line number in the file

  1. Using __METHOD__
class Toyota {
    public function getMethod() {
        return __METHOD__;
    }
}

$car = new Toyota();
echo $car->getMethod(); // Output: Toyota::getMethod

  1. Using __NAMESPACE__
namespace FordNamespace;

echo __NAMESPACE__; 
// Output: FordNamespace

  1. Using __TRAIT__
trait HondaTrait {
    public function getTraitName() {
        return __TRAIT__;
    }
}

class Sedan {
    use HondaTrait;
}

$vehicle = new Sedan();
echo $vehicle->getTraitName(); // Output: HondaTrait

  1. Using ClassName::class
namespace Lamborghini;

class Aventador {}

echo Aventador::class; 
// Output: Lamborghini\Aventador

Tutorials dojo strip
Scroll to Top