← Back to Chapters

PHP Magic Constants

? PHP Magic Constants

? Quick Overview

PHP provides a set of magic constants that change depending on where they are used. They always start and end with double underscores (__).

? Key Concepts

  • Magic constants are predefined by PHP
  • Their values depend on context
  • Resolved automatically at runtime
  • Extremely useful for debugging and logging

? Syntax & Theory

Unlike user-defined constants, magic constants do not need to be defined. PHP replaces them with contextual values while executing the script.

? Code Example

? View Code Example
// Demonstrating PHP magic constants
<?php
namespace MyApp {
    echo "__LINE__: " . __LINE__ . "<br>";
    echo "__FILE__: " . __FILE__ . "<br>";
    echo "__DIR__: " . __DIR__ . "<br>";

    function demo() {
        echo "__FUNCTION__: " . __FUNCTION__ . "<br>";
    }
    demo();

    class Test {
        public function show() {
            echo "__CLASS__: " . __CLASS__ . "<br>";
            echo "__METHOD__: " . __METHOD__ . "<br>";
        }
    }
    $obj = new Test();
    $obj->show();

    trait ExampleTrait {
        public function who() {
            echo "__TRAIT__: " . __TRAIT__ . "<br>";
        }
    }

    class Demo {
        use ExampleTrait;
    }
    (new Demo())->who();

    echo "__NAMESPACE__: " . __NAMESPACE__ . "<br>";
}
?>

? Live Output / Explanation

Each magic constant outputs information related to its execution context such as file path, line number, function name, class, method, trait, or namespace.

? List of Magic Constants

  • __LINE__ – Current line number
  • __FILE__ – Full file path
  • __DIR__ – Directory path
  • __FUNCTION__ – Function name
  • __CLASS__ – Class name
  • __METHOD__ – Class method
  • __TRAIT__ – Trait name
  • __NAMESPACE__ – Namespace name

?️ Use Cases

  • Error logging and debugging
  • Tracking execution flow
  • Framework-level diagnostics
  • File path handling

✅ Tips & Best Practices

  • Use magic constants in logs for clarity
  • Prefer __DIR__ over relative paths
  • Combine with namespaces in large projects
  • Helpful in debugging complex applications

? Try It Yourself

  • Create a function and print __FUNCTION__
  • Create a class and display __CLASS__
  • Add a namespace and print __NAMESPACE__
  • Echo __FILE__ and __DIR__