Magic constants are keywords that are replaced with information about
their own location in the source code: their file and line, and the
function, class, trait, namespace, or property hook enclosing them.
Despite their name, they are not actual constants:
defined() and constant() do not
recognize them, and a constant of the same name created with
define() does not affect them. They are case-insensitive.
When used outside of the relevant context (e.g. __CLASS__
outside of a class), they are replaced with an empty string.
| Name | Description |
|---|---|
__LINE__ |
The line number on which it is written. |
__FILE__ |
The full path and filename of the file in which it is written, with symlinks resolved. |
__DIR__ |
The directory of the file, equivalent to
dirname(__FILE__). It has no trailing slash
unless it is the root directory.
|
__FUNCTION__ |
The name of the function in which it is written, including its namespace
(e.g. Foo\bar).
Inside a method, only the method name.
For anonymous functions, a name generated by the engine that includes
where the closure was defined (as of PHP 8.4.0; previously
{closure}).
|
__CLASS__ |
The name of the class in which it is written, including its namespace
(e.g. Foo\Bar).
Inside a trait, the name of the class using the trait.
For anonymous classes,
a name generated by the engine.
To get the name of the class a method was called on, use
static::class.
|
__TRAIT__ |
The trait name, including its namespace (e.g. Foo\Bar).
|
__METHOD__ |
The class and method name of the method in which it is written
(e.g. Foo\Bar::baz).
Inside a trait, the trait name is used instead of the class name.
Outside of a method, the same as __FUNCTION__.
|
__PROPERTY__ |
The name of the property, when used inside a property hook. Available as of PHP 8.4.0. |
__NAMESPACE__ |
The name of the current namespace. |
Example #1 Using magic constants
<?php
namespace App;
function helper()
{
echo __FUNCTION__, "\n";
echo __METHOD__, "\n";
}
trait Greets
{
public function greet()
{
echo __CLASS__, "\n";
echo __TRAIT__, "\n";
echo __METHOD__, "\n";
echo __FUNCTION__, "\n";
}
}
class Greeter
{
use Greets;
}
helper();
(new Greeter)->greet();
echo __NAMESPACE__, "\n";The above example will output:
App\helper App\helper App\Greeter App\Greets App\Greets::greet greet App