Magic Constants
Magic constants are predefined constants that change depending on where they are used.
PHP provides several magic constants whose value depends on the context. Their names begin and end with double underscores.
| Constant | Description |
|---|---|
__LINE__ | The current line number. |
__FILE__ | The full path of the file. |
__FUNCTION__ | The current function name. |
__CLASS__ | The current class name. |
Example
Loading editor…
Press Run to execute the code.
When to use it
- Log messages that include the file and line they came from (__FILE__, __LINE__).
- Framework helpers that report the current class or method (__CLASS__, __METHOD__).
- Quick debugging — printing __FUNCTION__ to trace which function produced output.
More examples
Line and file
__LINE__ and __FILE__ resolve to exactly where they appear in the source.
<?php
echo "Error on line " . __LINE__ . "\n";
echo "In file " . __FILE__;Class and method
__CLASS__ and __FUNCTION__ describe the current class and method at runtime.
<?php
class User {
public function whoami() {
return __CLASS__ . "::" . __FUNCTION__;
}
}
echo (new User)->whoami(); // User::whoami__DIR__ for file paths
__DIR__ is the directory of the current file — ideal for require/include paths.
<?php
// Path relative to THIS file's folder
$path = __DIR__ . "/config.php";
echo $path;
Discussion