PHP magic constants are predefined constants that change based on their usage within a script.
These constants provide information about different aspects of the script, such as file paths, line numbers, and function names.
Magic constants are always prefixed with two underscores (__).
Here are some commonly used PHP magic constants:
1. __LINE__: Represents the current line number of the file.
<?php
echo "This is line number " . __LINE__;
?>
2. __FILE__: Represents the full path and filename of the file.
<?php
echo "The current file is " . __FILE__;
?>
3. __DIR__: Represents the directory of the file.
<?php
echo "The current directory is " . __DIR__;
?>
4. __FUNCTION__: Represents the name of the current function.
<?php
function exampleFunction() {
echo "The current function is " . __FUNCTION__;
}
exampleFunction();
?>
5. __CLASS__: Represents the name of the current class.
<?php
class ExampleClass {
public function showClassName() {
echo "The current class is " . __CLASS__;
}
}
$obj = new ExampleClass();
$obj->showClassName();
?>
6. __METHOD__: Represents the name of the current method (in a class).
<?php
class ExampleClass {
public function showMethodName() {
echo "The current method is " . __METHOD__;
}
}
$obj = new ExampleClass();
$obj->showMethodName();
?>
7. __NAMESPACE__: Represents the name of the current namespace.
<?php
namespace MyNamespace;
echo "The current namespace is " . __NAMESPACE__;
?>
These magic constants provide useful information for debugging and logging purposes, and they dynamically reflect the context in which they are used.