PHP
๐ช Magic Constants in PHP
Magic Constants are predefined constants automatically provided by PHP that resolve to different values depending on where they are used in the codebase. Unlike standard constants, their values change dynamically based on the current execution context.
-
Key Feature: Magic constants always start and end with two underscores (e.g.
__LINE__). They answer spatial questions like "Which line, file, function, or class am I currently executing?"
โญ Commonly Used Magic Constants
๐น __LINE__
Returns the current line number of the file where this constant is invoked. Useful for error tracking and debugging.
echo "Current line number: " . __LINE__;
๐น __DIR__
Returns the absolute directory path of the script file. It does not include the file name itself (equivalent to dirname(__FILE__)).
echo "Current directory: " . __DIR__;
include __DIR__ . "/Ayarlar/baglantilar.php";
๐น __FILE__
Returns the full, absolute file path including the file name of the running script.
echo "Full file path: " . __FILE__;
๐น __FUNCTION__
Returns the name of the function currently executing. Returns an empty string if used outside a function.
function sistemKontrol() {
echo "Executing function: " . __FUNCTION__;
}
sistemKontrol(); // Outputs: Executing function: sistemKontrol
๐น __CLASS__
Returns the name of the current class, including the namespace if applicable.
class Veritabani {
public function sinifAdiAl() {
echo "Active Class: " . __CLASS__;
}
}
$vt = new Veritabani();
$vt->sinifAdiAl(); // Outputs: Active Class: Veritabani
๐น __METHOD__
Returns the class name combined with the method name where it is declared.
class Kullanici {
public function girisYap() {
echo "Running method: " . __METHOD__;
}
}
$kullanici = new Kullanici();
$kullanici->girisYap(); // Outputs: Running method: Kullanici::girisYap
๐น __TRAIT__
Returns the name of the trait currently being executed, including its namespace.
trait Loglayici {
public function logOlustur() {
echo "Active Trait: " . __TRAIT__;
}
}
๐น __NAMESPACE__
Returns the string name of the current active namespace scope.
namespace App\Services;
echo "Current Namespace: " . __NAMESPACE__; // Outputs: App\Services
-
๐ Brief Summary
- Magic constants provide context-aware dynamic values based on location in code.
-
Widely used in dynamic file inclusions (
__DIR__), logging systems, and error debugging. - They are case-insensitive, but writing them in UPPERCASE with double underscores is standard practice.
