PHP Magic Constants
PHP provides several predefined constants called Magic Constants that change their values depending on where they are used. These constants start and end with double underscores (__)
Common Magic Constants
<?php
// File path and line information
echo "Current file: " . __FILE__ . "\n";
echo "Current line: " . __LINE__ . "\n";
// Directory information
echo "Directory of the file: " . __DIR__ . "\n";
// Function and class information
function testFunction() {
echo "Current function: " . __FUNCTION__ . "\n";
}
class TestClass {
public function testMethod() {
echo "Current class: " . __CLASS__ . "\n";
echo "Current method: " . __METHOD__ . "\n";
}
}
testFunction();
$obj = new TestClass();
$obj->testMethod();
?>
Magic Constants Explained:
__LINE__
: Current line number of the file__FILE__
: Full path and filename of the file__DIR__
: Directory of the file__FUNCTION__
: Name of the current function__CLASS__
: Name of the current class__METHOD__
: Name of the current class method__NAMESPACE__
: Name of the current namespace__TRAIT__
: Name of the current trait
Practical Example
<?php
namespace App\Controllers;
trait LoggerTrait {
public function log($message) {
echo "[" . __TRAIT__ . "] " . $message . "\n";
}
}
class UserController {
use LoggerTrait;
public function __construct() {
echo "Namespace: " . __NAMESPACE__ . "\n";
$this->log("Controller initialized");
}
}
$controller = new UserController();
?>
Output:
Namespace: App\Controllers [LoggerTrait] Controller initialized