PHP : Magic Constants

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__:

 

  •   Returns the current line number of the file.
  •   Example:

    
     echo __LINE__; // Output: Current line number
    

2. __FILE__:

 

  •   Returns the full path and filename of the file.
  •   Example:

    
     echo __FILE__; // Output: Current file name with full path
     

3.  __DIR__:

  •   Returns the directory of the file.
  •   Example:

     
     echo __DIR__; // Output: Current directory name
     

4. __FUNCTION__:

 

  •   Returns the name of the current function.
  •   Example:

    
     function test() {
         echo __FUNCTION__; // Output: test
     }

     

5. __CLASS__:

 

  •   Returns the name of the current class.
  •   Example:

     
     class MyClass {
         public function displayClassName() {
             echo __CLASS__; // Output: MyClass
         }
     }

     

6. __METHOD__:

 

  •  Returns the name of the current method within a class.
  •  Example:

    
     class MyClass {
         public function displayMethodName() {
             echo __METHOD__; // Output: MyClass::displayMethodName
         }
     }

     

7. __NAMESPACE__:

 

  •   Returns the name of the current namespace.
  •   Example:

     
     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.