PHP : Constants

In PHP, constants are like variables, but their values cannot be changed once they are defined. Constants are useful for defining values that are used frequently throughout a script and should remain constant throughout its execution. Here's how you define and use constants in PHP:

1. Defining Constants:

 

  •   Constants are defined using the `define()` function or the `const` keyword.
  •   The syntax for `define()` is `define(name, value, case_insensitive)`.
  •    The syntax for `const` is `const name = value;`.
  •    Example:

    
     define("PI", 3.14);
     const MAX_SIZE = 100;

     

2. Accessing Constants:

 

  •    Constants are accessed without the dollar sign (`$`) prefix, unlike variables.
  •    Example:

    
     echo PI; // Output: 3.14
     echo MAX_SIZE; // Output: 100

  

3. Case Sensitivity:

 

  •   Constants defined with `define()` are case-insensitive by default unless the third argument is set to `true`.
  •   Constants defined with `const` are always case-sensitive.
  •   Example:

    
     define("GREETING", "Hello", true); // Case-insensitive
     const MESSAGE = "Welcome"; // Case-sensitive
     echo GREETING; // Output: Hello
     echo MESSAGE; // Output: Welcome

     

4. Magic Constants:

 

  •  PHP also provides a set of predefined constants called "magic constants" that change based on their usage context.
  •  Some common magic constants include `__LINE__`, `__FILE__`, `__DIR__`, `__FUNCTION__`, `__CLASS__`, `__METHOD__`, and `__NAMESPACE__`.
  •   Example:

   
     echo __LINE__; // Output: Current line number
     echo __FILE__; // Output: Current file name

    

Constants provide a way to define and use values that remain constant throughout the execution of a PHP script. They are useful for defining configuration settings, predefined values, and other constants that should not be modified during script execution.