Magical Constants in PHP: Explained with Examples
Magical constants in PHP are predefined constants that provide dynamic information about the code and its context. They are “magical” because they change based on where they are used. Unlike regular constants that are resolved at runtime, magical constants are resolved at compile time. Here’s a breakdown of the most common magical constants in PHP, along with examples.
- LINE
Description: Returns the current line number of the file.
Example
<?php
echo "The current line number is " . __LINE__;
?>
Output:
The current line number is 2
- FILE
Description: Returns the full path and filename of the file.
Example:
<?php
echo "The file path is " . __FILE__;
?>
Output:
The file path is /var/www/html/script.php
- DIR
Description: Returns the directory of the file.
Example
<?php
echo "The directory is " . __DIR__;
?>
Output:
The directory is /var/www/html
- FUNCTION
Description: Returns the name of the current function.
Example
<?php
function myFunction() {
echo "Function name is " . __FUNCTION__;
}
myFunction();
?>
Output:
Function name is myFunction
- CLASS
Description: Returns the name of the current class, including the namespace.
Example
<?php
class MyClass {
public function showClass() {
echo "Class name is " . __CLASS__;
}
}
$obj = new MyClass();
$obj->showClass();
?>
Output:
Class name is MyClass
- METHOD
Description: Returns the name of the current class method.
Example
<?php
class MyClass {
public function myMethod() {
echo "Method name is " . __METHOD__;
}
}
$obj = new MyClass();
$obj->myMethod();
?>
Output:
Method name is MyClass::myMethod
- TRAIT
Description: Returns the name of the current trait.
Example:
<?php
trait MyTrait {
public function showTrait() {
echo "Trait name is " . __TRAIT__;
}
}
class MyClass {
use MyTrait;
}
$obj = new MyClass();
$obj->showTrait();
?>
Output:
Trait name is MyTrait
- NAMESPACE
Description: Returns the name of the current namespace.
Example
<?php
namespace MyNamespace;
class MyClass {
public function showNamespace() {
echo "Namespace is " . __NAMESPACE__;
}
}
$obj = new MyClass();
$obj->showNamespace();
?>
Output:
Namespace is MyNamespace
- ::class
Description: Returns the fully qualified name of a class.
Example
<?php
namespace MyNamespace;
class MyClass {}
echo MyClass::class;
?>
Output:
MyNamespace\MyClass
Magical constants in PHP are handy for dynamically fetching information about the code, like file paths, line numbers, class names, and namespaces. These constants help developers write more flexible and maintainable code.
Keep Learning 🙂