Lesson 7: PHP Magic Constants
Have a Question?
Latest Articles

Lesson 7: PHP Magic Constants
PHP Magic Constants are powerful built-in constants that provide contextual information during code execution. Unlike regular constants, their values change depending on where they are used.
What Are Magic Constants?
Magic Constants are predefined constants in PHP that start and end with double underscores (__
). They return specific information like file names, line numbers, class names, and more.
Most Common PHP Magic Constants
1. __LINE__
Returns the current line number in the file.
📌 Example:
echo "You are on line " . __LINE__;
2. __FILE__
Returns the full path and filename of the file.
📌 Example:
echo "File path: " . __FILE__;
3. __DIR__
Returns the directory of the file.
📌 Example:
echo "Directory: " . __DIR__;
4. __FUNCTION__
Returns the name of the function.
📌 Example:
function test() { echo "Function name: " . __FUNCTION__; } test();
5. __CLASS__
Returns the class name.
📌 Example:
class MyClass { public function show() { echo "Class: " . __CLASS__; } }
6. __METHOD__
Returns the class method name.
📌 Example:
class MyClass { public function show() { echo "Method: " . __METHOD__; } }
7. __NAMESPACE__
Returns the current namespace.
📌 Example:
namespace MyApp; echo "Namespace: " . __NAMESPACE__;
When Should You Use Them?
For debugging and logging errors.
To get dynamic file paths.
When documenting code automatically.
While working on dynamic class loaders.
Benefits of Magic Constants
- ✅ Easy to track and debug code.
- ✅ Add flexibility and automation.
- ✅ Improve maintainability and structure.
Conclusion
PHP Magic Constants give developers access to useful runtime information. When used wisely, they help you write smarter, cleaner, and more maintainable PHP code.
Important links Portfolio
Share with your friends