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.

ConstantDescription
__LINE__The current line number.
__FILE__The full path of the file.
__FUNCTION__The current function name.
__CLASS__The current class name.

Example

Try it yourself
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.

Example · php
<?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.

Example · php
<?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.

Example · php
<?php
// Path relative to THIS file's folder
$path = __DIR__ . "/config.php";
echo $path;

Discussion

  • Be the first to comment on this lesson.