PHP constants are immutable values that do not change during script execution. They are useful for storing fixed values like configuration settings, database credentials, or mathematical constants.
What Are PHP Constants?
A constant in PHP is a name assigned to a value that cannot be changed after it has been defined.
Key Features of Constants:
✅ Values remain unchanged throughout execution ✅ No $ symbol before the name (unlike variables) ✅ Automatically global across the entire script
Constants can also be used inside classes using the const keyword.
<?php
class Car {
const BRAND = "Toyota";
}
echo Car::BRAND; // Outputs: Toyota
?>
Checking if a Constant is Defined
Use the defined() function to check whether a constant exists.
<?php
define("API_KEY", "12345");
if (defined("API_KEY")) {
echo "API_KEY is defined";
} else {
echo "API_KEY is not defined";
}
?>
Best Practices for Using Constants in PHP
✅ Use uppercase names for constants (DB_HOST, MAX_USERS) ✅ Group related constants together in configuration files ✅ Avoid using magic numbers—use named constants instead ✅ Always check if a constant exists before using it