Php Magic Constants

Php Magic Constants

Php Magic Constants

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:

  1. __LINE__: Returns the current line number of the file.
				
					echo "This is line " . __LINE__ . " in " . __FILE__;
// output: This is line 1 in /path/to/file.php 

				
			

 

  1. __FILE__: Returns the full path and filename of the file.
				
					echo "The full path to this file is " . __FILE__;
// output: The full path to this file is /path/to/file.php

				
			
  1. __DIR__: Returns the directory of the file.
				
					echo "The directory of this file is " . __DIR__;
// output: The directory of this file is /path/to/

				
			
  1. __FUNCTION__: Returns the name of the current function.
				
					function myFunction() {
    echo "The current function is " . __FUNCTION__;
}
myFunction(); // output: The current function is myFunction

				
			
  1. __CLASS__: Returns the name of the current class.
				
					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

				
			
  1. __METHOD__: Returns the name of the current method.
				
					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.

Join To Get Our Newsletter
Spread the love