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.
__
.
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. |
<?php echo "This is line number: " . __LINE__; echo "<br>This file is: " . __FILE__; echo "<br>This directory is: " . __DIR__; ?>
<?php function test() { echo "Function name: " . __FUNCTION__; } test(); ?>
<?php class Demo { public function showInfo() { echo "Class name: " . __CLASS__; echo "<br>Method name: " . __METHOD__; } } $obj = new Demo(); $obj->showInfo(); ?>
Since magic constants are built-in and dynamic, you cannot override them using define()
or any other method.
__
.Want more? Try using these constants inside included files and see how they behave differently!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!