PHP magic constants are predefined constants that change their values depending on where they are used. These constants are not defined using the define()
function and are automatically available in PHP.
Here are some commonly used magic constants:
__LINE__
- Represents the current line number in the file.__FILE__
- Represents the full path and name of the file.__DIR__
- Represents the directory of the file.__FUNCTION__
- Represents the function name.__CLASS__
- Represents the class name.__METHOD__
- Represents the method name.__NAMESPACE__
- Represents the current namespace.The following example demonstrates how to use some of the magic constants in PHP.
<?php
echo "This is line: " . __LINE__ . "<br>"; // Line number
echo "This file is located at: " . __FILE__ . "<br>"; // Full file path
echo "This file is in directory: " . __DIR__ . "<br>"; // Directory path
?>
This is line: 21
This file is located at: /var/www/html/example.php
This file is in directory: /var/www/html
Magic constants are useful for debugging and creating dynamic file paths. They are automatically evaluated and can provide context for error handling, file inclusion, and other operations.