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:
Name | Description |
---|---|
__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::class | Return 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.