In PHP, there are several predefined constants called “magic constants” that provide information about the script, such as its file path, line number, and function name. These constants are prefixed with two underscores (__) and can be used anywhere in a PHP script.
Here are some of the commonly used magic constants in PHP:
echo "This is line " . __LINE__ . " in " . __FILE__;
// output: This is line 1 in /path/to/file.php
echo "The full path to this file is " . __FILE__;
// output: The full path to this file is /path/to/file.php
echo "The directory of this file is " . __DIR__;
// output: The directory of this file is /path/to/
function myFunction() {
echo "The current function is " . __FUNCTION__;
}
myFunction(); // output: The current function is myFunction
class MyClass {
public function printClassName() {
echo "The name of this class is " . __CLASS__;
}
}
$myObject = new MyClass();
$myObject->printClassName(); // output: The name of this class is MyClass
class MyClass {
public function printMethodName() {
echo "The name of this method is " . __METHOD__;
}
}
$myObject = new MyClass();
$myObject->printMethodName(); // output: The name of this method is MyClass::printMethodName
Using magic constants can be helpful in debugging or logging your PHP scripts. However, it’s important to use them judiciously and not rely too heavily on them, as they can make your code less readable and maintainable.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.