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.

PHP
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__)).

PHP
echo "Current directory: " . __DIR__;
include __DIR__ . "/Ayarlar/baglantilar.php";

๐Ÿ”น __FILE__
Returns the full, absolute file path including the file name of the running script.

PHP
echo "Full file path: " . __FILE__;

๐Ÿ”น __FUNCTION__
Returns the name of the function currently executing. Returns an empty string if used outside a function.

PHP
function sistemKontrol() {
    echo "Executing function: " . __FUNCTION__;
}

sistemKontrol(); // Outputs: Executing function: sistemKontrol

๐Ÿ”น __CLASS__
Returns the name of the current class, including the namespace if applicable.

PHP
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.

PHP
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.

PHP
trait Loglayici {
    public function logOlustur() {
        echo "Active Trait: " . __TRAIT__;
    }
}

๐Ÿ”น __NAMESPACE__
Returns the string name of the current active namespace scope.

PHP
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.