PHP provides a set of magic constants that change depending on where they are used. They always start and end with double underscores (__).
Unlike user-defined constants, magic constants do not need to be defined. PHP replaces them with contextual values while executing the script.
// 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>";
}
?>
Each magic constant outputs information related to its execution context such as file path, line number, function name, class, method, trait, or namespace.
__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__DIR__ over relative paths__FUNCTION____CLASS____NAMESPACE____FILE__ and __DIR__