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__
PHP

  1. Using __DIR__
PHP

  1. Using __FILE__
PHP

  1. Using __FUNCTION__
PHP

  1. Using __LINE__
PHP

  1. Using __METHOD__
PHP

  1. Using __NAMESPACE__
PHP

  1. Using __TRAIT__
PHP

  1. Using ClassName::class
PHP

Tutorials dojo strip