Skip to content

PHP Tutorial Variables and Constants

Magic Constants

Lesson 32 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Magic constants are special built-in constants whose value depends on where in your code you use them. They start and end with two underscores.

ConstantGives you
__LINE__The current line number
__FILE__The full path of the current file
__DIR__The folder of the current file
__FUNCTION__The name of the current function
__CLASS__The name of the current class
__METHOD__The class and method name
__NAMESPACE__The current namespace

Example

index.php
PHP
<?php
function showWhere(): void
{
    echo "Function: " . __FUNCTION__ . "\n";
    echo "Line: " . __LINE__ . "\n";
}

showWhere();
echo "File name: " . basename(__FILE__);
Output
OUTPUT
Function: showWhere
Line: 5
File name: index.php

The one you will use most: __DIR__

When you include another file, a path like "config.php" depends on where the script was started. __DIR__ always gives a path that is relative to the current file, so it never breaks.

index.php
PHP
<?php
require __DIR__ . "/config.php";

You will use this a lot in Include and Require.

In classes

index.php
PHP
<?php
class Report
{
    public function title(): string
    {
        return __CLASS__ . " / " . __METHOD__;
    }
}

echo (new Report())->title();
Output
OUTPUT
Report / Report::title
lightbulb
Logging is a good use
A log message such as "Failed in " . __METHOD__ . " line " . __LINE__ tells you exactly where the problem happened.