Magic Constants in PHP

Magic Constants

In PHP, magic constants are special, predefined constants that change their values dynamically based on where they are used within the script’s context. They are “magic” because they are defined at compile time, unlike regular constants (which you’d define yourself) that are defined at runtime.

This means their values can change depending on where they are used in your code. Magic constants are primarily used for debugging, logging, and obtaining information about the current location in the PHP code.

Characteristics of Magic Constants

  • Dynamic Value: Unlike regular constants, their values are not fixed but automatically update depending on their location in the code (e.g., current line number, file name).
  • Syntax: All magic constants start and end with a double underscore (__), except for ClassName::class.
  • Case-Insensitive: For most, __LINE__ is the same as __line__.
  • Resolution: They are resolved at compile time, not runtime.

List of Magic Constants in PHP

The standard magic constants available in PHP are:

  1. __LINE__: Provides the current line number in the file.
  2. __FILE__: Gives the full path and filename of the script, resolving symlinks.
  3. __DIR__: Represents the directory of the file, similar to dirname(__FILE__).
  4. __FUNCTION__: Returns the name of the function currently being executed, or {closure}for anonymous functions.
  5. __CLASS__: Provides the class name, including its namespace.
  6. __TRAIT__: Returns the name of the trait currently being used, including its namespace.
  7. __METHOD__: Yields the class method name, formatted as ClassName::methodName.
  8. __NAMESPACE__: Shows the name of the current namespace.
  9. ClassName::class: A special case that provides the fully qualified class name.