Constants
Constants in PHP are used to store values that do not change during the execution of a script. Unlike variables, once a constant is defined, its value cannot be modified or undefined. Constants are useful for storing configuration settings, fixed values, or any data that should remain the same throughout your application.
Defining
Constants
You can define constants using the define()
function or the const
keyword.
Using define()
<?php
define(
"SITE_NAME",
"My Web Blog");
echo SITE_NAME;
?>
Using const
<?php
const
PI =
3.14159;
echo PI;
?>
Characteristics
of Constants
·
Constant names are
case-sensitive by default.
·
They do not start with a $
sign.
·
They can store scalar
values like integers, strings, floats, and booleans.
·
They are globally
accessible anywhere in the script.
Example
with Constants
<?php
define(
"MAX_USERS",
100);
echo
"The maximum number of users is: " . MAX_USERS;
const
VERSION =
"1.0.0";
echo
"\nCurrent version: " . VERSION;
?>
Output:
The maximum number
of users
is:
100
Current
version:
1.0.0