What are the constants in PHP

What are the constants in PHP?

  • Constants are like variables, but their values cannot be changed once they are defined.  
  • They are typically used for values that should remain fixed throughout the script.
How to Declaring Constants:
  • Use the define() function to declare a constant.
  • Example:
define("PI", 3.14159); 
define("SITE_URL", "https://www.example.com");
Accessing Constants:
  • Access the value of a constant using its name directly.

  • Example:
echo PI; // Outputs: 3.14159
echo SITE_URL; // Outputs: https://www.example.com
Benefits of Using Constants:
  • Improved Readability: Make your code more readable and maintainable.
  • Centralized Values: Easily change the value of a constant in one place, and it will be updated everywhere it’s used.
  • Enhanced Code Organization: Helps keep your code cleaner and more organized.
  • Reduced Errors: Prevents accidental modification of important values.
Real life example of constant:
<?php
define("MAX_ATTEMPTS", 3);
if ($login_attempts > MAX_ATTEMPTS) {
echo "Login failed. Too many attempts.";
}
?>

In this example, MAX_ATTEMPTS is defined as a constant with a value of 3. This makes it easy to change the maximum number of login attempts allowed in one place, improving code maintainability.

Scroll to Top