In PHP, magic constants are predefined constants that change based on their usage context. These constants provide information about the script, such as the current file, line number, function, class, method, or namespace. Here's an overview of some commonly used magic constants in PHP:
1. __LINE__:
echo __LINE__; // Output: Current line number
2. __FILE__:
echo __FILE__; // Output: Current file name with full path
3. __DIR__:
echo __DIR__; // Output: Current directory name
4. __FUNCTION__:
function test() {
echo __FUNCTION__; // Output: test
}
5. __CLASS__:
class MyClass {
public function displayClassName() {
echo __CLASS__; // Output: MyClass
}
}
6. __METHOD__:
class MyClass {
public function displayMethodName() {
echo __METHOD__; // Output: MyClass::displayMethodName
}
}
7. __NAMESPACE__:
namespace MyNamespace;
echo __NAMESPACE__; // Output: MyNamespace
These magic constants provide convenient ways to access information about the current script, function, class, or namespace, which can be useful for debugging, logging, or generating dynamic content. By using magic constants, you can make your PHP scripts more dynamic and flexible.