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
).
The List of Magic Constants and Their Descriptions
Constant | Description |
---|---|
__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::class | Outputs 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.
- Using
__CLASS__
class Ducati { public function getClassName() { return __CLASS__; } } $motorbike = new Ducati(); echo $motorbike->getClassName(); // Output: Ducati
- Using
__DIR__
echo "The directory is: " . __DIR__; // Output: Displays the directory path of the current file
- Using
__FILE__
echo "The file path is: " . __FILE__; // Output: Displays the full path and file name
- Using
__FUNCTION__
function harleyFunction() { return __FUNCTION__; } echo harleyFunction(); // Output: harleyFunction
- Using
__LINE__
echo "This is line number: " . __LINE__; // Output: Displays the current line number in the file
- Using
__METHOD__
class Toyota { public function getMethod() { return __METHOD__; } } $car = new Toyota(); echo $car->getMethod(); // Output: Toyota::getMethod
- Using
__NAMESPACE__
namespace FordNamespace; echo __NAMESPACE__; // Output: FordNamespace
- Using
__TRAIT__
trait HondaTrait { public function getTraitName() { return __TRAIT__; } } class Sedan { use HondaTrait; } $vehicle = new Sedan(); echo $vehicle->getTraitName(); // Output: HondaTrait
- Using
ClassName::class
namespace Lamborghini; class Aventador {} echo Aventador::class; // Output: Lamborghini\Aventador