PHP Tutorial



PHP MAGIC CONSTANTS


🪄 PHP Magic Constants

Magic constants in PHP are predefined constants that change depending on where they are used. These are extremely useful for debugging, file handling, and code tracking.

Note: Magic constants start and end with double underscores __.

📋 List of PHP Magic Constants

Constant Description
__LINE__ Returns the current line number in the file.
__FILE__ Returns the full path and filename of the file.
__DIR__ Returns the directory of the file.
__FUNCTION__ Returns the name of the current function.
__CLASS__ Returns the name of the current class.
__METHOD__ Returns the name of the current class method.
__NAMESPACE__ Returns the current namespace name.
__TRAIT__ Returns the name of the current trait.

🔍 Commonly Used Magic Constants

<?php
echo "This is line number: " . __LINE__;
echo "<br>This file is: " . __FILE__;
echo "<br>This directory is: " . __DIR__;
?>
  

🧠 Inside a Function

<?php
function test() {
  echo "Function name: " . __FUNCTION__;
}
test();
?>
  

🏛️ Inside a Class

<?php
class Demo {
  public function showInfo() {
    echo "Class name: " . __CLASS__;
    echo "<br>Method name: " . __METHOD__;
  }
}

$obj = new Demo();
$obj->showInfo();
?>
  
Tip: Magic constants are super helpful when debugging or building logging systems.

🚫 You Cannot Redefine Them

Since magic constants are built-in and dynamic, you cannot override them using define() or any other method.

📌 Summary

  • Start and end with __.
  • Provide metadata like file path, class, method, etc.
  • Change value depending on context of use.
  • Common in debugging, logging, and dynamic apps.

Want more? Try using these constants inside included files and see how they behave differently!


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review