Constants
Constants
Constants are identifiers used to store fixed values that cannot be changed or removed during program execution.
How to Define Constants
PHP provides two ways to create constants:
- Using the define() function
- Using the const keyword
define() Function
The define() function is used to create a constant with a fixed value that cannot be changed during program execution.
A constant created using define() keeps the same value throughout the script.
Example
// Creating constants using define() function
define("SITE_NAME", "MyWebsite");
define("VERSION", "1.0");
// Displaying constants
echo "Site Name: " . SITE_NAME;
echo "\n";
echo "Version: " . VERSION;
?>
const Keyword
The const keyword is used to create a constant with a fixed value that remains unchanged throughout the script.
The const keyword defines a constant at compile-time, meaning its value is set before the script runs.
Key Features
- Must be declared at the top-level scope
- Cannot be used inside functions, loops, if/else, or try/catch blocks (in general usage)
- Can be used to define class constants
- Constants are case-sensitive
Example
// Constant using const keyword
const SITE_NAME = "MyWebsite";
const PI = 3.14;
echo SITE_NAME;
echo "\n";
echo PI;
?>