PHP Tutorial



CONSTANTS IN PHP


πŸ”’ PHP Constants

Constants in PHP are like variables, but once they are defined, their values cannot be changed. They're great for storing fixed values like configuration settings or mathematical values.

Note: Constant names are by convention written in uppercase letters.

πŸ› οΈ How to Define a Constant

You can define a constant in PHP using the define() function:

<?php
  define("SITE_NAME", "Technorank");
  echo SITE_NAME; // Output: Technorank
?>
  

✨ Constant Characteristics

  • Constants do not require a $ symbol.
  • Once defined, constants cannot be changed or undefined.
  • Constants are globally accessible throughout the script.

πŸ“¦ Example with Conditional Use

Using constants to check conditions or configure app behavior:

<?php
  define("DEBUG_MODE", true);

  if (DEBUG_MODE) {
    echo "Debugging is enabled!";
  }
?>
  

🎯 Magic Constants in PHP

PHP also provides special built-in constants called Magic Constants, like:

  • __FILE__ β†’ Full path of the file.
  • __LINE__ β†’ Current line number.
  • __DIR__ β†’ Directory of the file.
<?php
  echo "This file is located at: " . __FILE__;
?>
  

πŸ“± Responsive Tip:

When using constants for configuration (like BASE_URL), structure your code to adjust for screen sizes with responsive CSS and conditional PHP rendering if needed.

🚫 Can Constants Be Overwritten?

No. Once a constant is defined using define(), trying to redefine it will not change its value:

<?php
  define("SITE_VERSION", "1.0");
  define("SITE_VERSION", "2.0"); // This will not overwrite the first one.
  echo SITE_VERSION; // Output: 1.0
?>
  

🧠 Summary

  • Use define("NAME", value); to create constants.
  • No $ symbol is needed before constant names.
  • Once set, they can’t be changed.
  • Accessible globally β€” use them wisely!

Quick Tip: Use constants to store database credentials or site-wide settings to avoid hardcoding values in multiple places.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review