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.
You can define a constant in PHP using the define()
function:
<?php define("SITE_NAME", "Technorank"); echo SITE_NAME; // Output: Technorank ?>
$
symbol.Using constants to check conditions or configure app behavior:
<?php define("DEBUG_MODE", true); if (DEBUG_MODE) { echo "Debugging is enabled!"; } ?>
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__; ?>
BASE_URL
), structure your code to adjust for screen sizes with responsive CSS and conditional PHP rendering if needed.
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 ?>
define("NAME", value);
to create constants.$
symbol is needed before constant names.Quick Tip: Use constants to store database credentials or site-wide settings to avoid hardcoding values in multiple places.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!