PHP CHAPTER 13

PHP Magic Constants

Magic constants are predefined PHP constants whose values can change depending on where they are used.

📘

What is it?

Magic constants are predefined PHP constants whose values can change depending on where they are used.

💡

Why do we use it?

They are useful for debugging and identifying code locations.

⚙️

How does it work?

PHP automatically provides values such as __FILE__, __DIR__, __LINE__, __FUNCTION__ and __CLASS__.

🧩

Syntax

PHP Syntax
__FILE__
__DIR__
__LINE__
💻

Example

PHP Example
<?php

echo __FILE__ . "<br>";
echo __DIR__ . "<br>";
echo __LINE__;

?>
🔍

Example Explained

__FILE__ returns the current file path. __DIR__ returns its directory. __LINE__ returns the current line number.
🚀

More Examples

<?php function testFunction() { echo __FUNCTION__; } testFunction(); ?>

⚠️ Important Rules

Magic constants use double underscores.

❌ Common Mistakes

Using the wrong number of underscores.

🌍 Real-World Use

Debugging, logging and framework development.

📝 Practice Exercise

Create a debug page displaying file, directory and line information.

💻 Try It Yourself

Write and run this PHP lesson inside the AIFA Coding Lab.

Open Coding Lab →