← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 18 of 24

PHP Magic Constants

What Are Magic Constants?

Magic constants are special identifiers, always wrapped in double underscores like __LINE__, whose value changes depending on exactly where in the code they're written. Unlike a regular constant defined once with define(), PHP resolves a magic constant fresh at each location it appears.

Example: What Are Magic Constants?

php
<?php
echo __LINE__;
?>

__LINE__, __FILE__ and __DIR__

__LINE__ gives the current line number and __FILE__ the full path of the file being executed, which together are the backbone of quick debug logging. __DIR__ gives just the containing directory — commonly used to build reliable include paths that don't depend on the current working directory.

Example: __LINE__, __FILE__ and __DIR__

php
<?php
echo __LINE__ . "\n";
echo __FILE__ . "\n";
echo __DIR__;
?>

__FUNCTION__ and __METHOD__

__FUNCTION__ returns the name of the function it's written inside, while __METHOD__ returns the class-qualified form, ClassName::methodName, when used inside a class method. This distinction matters for logging, since __METHOD__ immediately tells you which class the log line came from.

Example: __FUNCTION__ and __METHOD__

php
<?php
function greet() {
    echo __FUNCTION__ . "\n";
}
class Greeter {
    function hello() {
        echo __METHOD__;
    }
}
greet();
(new Greeter())->hello();
?>

__CLASS__ and __NAMESPACE__

__CLASS__ gives the fully-qualified name of the class it's written in — useful inside a trait or parent class where you want the actual instantiated class, not the one the code is physically defined in. __NAMESPACE__ returns the current namespace, handy for building namespace-relative class names.

Example: __CLASS__ and __NAMESPACE__

php
<?php
namespace App;

class Greeter {
    function whoAmI() {
        echo __CLASS__ . " in " . __NAMESPACE__;
    }
}
(new Greeter())->whoAmI();
?>

Practical Uses in Debugging and Logging

Combining several magic constants into one log message — file, line, and function — gives you an exact source location for every log entry without hardcoding anything, so the log stays accurate even after the file is renamed or the function is moved.

Example: Practical Uses in Debugging and Logging

php
<?php
function logMessage($msg) {
    echo "[" . __FILE__ . ":" . __LINE__ . "] " . __FUNCTION__ . ": $msg";
}
logMessage("Something happened");
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.