PHP Magic Constants

Summary: in this tutorial, you will learn about PHP magic constants that hold values change depending on where they are used.

Introduction to the PHP magic constants

In PHP, regular constants store values that don’t change during the execution of the script. PHP resolves the constants defined by the define() function at runtime and resolves the constants defined by the const keyword at compile time.

Besides the regular constants, PHP has some constants whose values change depending on where you use them. For example, the __LINE__ constant returns the current line number of the current script.

These constants are known as magic constants. Unlike regular constants, PHP resolves the magic constants at runtime.

The following table illustrates the magic constants in PHP:

NameDescription
__LINE__Return the current line number of the file.
__FILE__Return the full path and filename of the file or include.
__DIR__Return the directory of the file or include. It’s equivalent to dirname(__FILE__). The __DIR__ doesn’t have a trailing slash (/) unless it’s the root directory.
__FUNCTION__Return function name, or {closure} for anonymous functions.
__CLASS__Return the class name that also includes the namespace.
__TRAIT__Return the trait name that includes the namespace
__METHOD__Return the name of the current instance method.
__NAMESPACE__Return the name of the current namespace.
ClassName::classReturn the fully qualified class name.

PHP magic constant example

The following example shows the values of the above magic constants:

<?php

namespace App;

class HttpRequest
{
    public function __construct()
    {
        echo 'The current class name is ' .  __CLASS__ . '<br>';
    }
    public function isPost()
    {
        echo 'The current method is ' . __METHOD__ . '<br>';
        
        return $_SERVER['REQUEST_METHOD'];
    }
}

$request = new HttpRequest();

$request->isPost();

echo 'The current namespace is ' . __NAMESPACE__ . '<br>';
echo 'The fully qualified class name is '  . HttpRequest::class . '<br>';
echo 'The current file is ' . __FILE__ . '<br>';
echo 'The current line is ' . __LINE__ . '<br>';
echo 'The current directory is ' . __DIR__  . '<br>';Code language: HTML, XML (xml)

Output:

The current class name is App\HttpRequest
The current method is App\HttpRequest::isPost
The current namespace is App
The fully qualified class name is App\HttpRequest
The current file is C:\xampp\htdocs\phptutorial\class.php
The current line is 29
The current directory is C:\xampp\htdocs\phptutorial\Code language: plaintext (plaintext)

Summary

  • PHP magic constants hold values resolved at runtime, not compile time.
  • The values of the magic constants change depending on where they’re used.
Did you find this tutorial useful?