PHP: Constants
In PHP, constants are names (identifiers) defined for simple values. Once defined, the value of a constant does not change throughout the program.
Contrast to variables, PHP constants DO NOT start with a $
(dollar) sign. But as with variables, their names also begin either with an alphabet (a-z,A-Z)
or with an underscore (_)
. Constant names may contain alphabets (a-z,A-Z)
, numbers (0-9)
and underscores (_)
but they cannot start with a number and cannot contain any other special characters beside the underscore (_)
. By convention, constant names are typed in all caps. PHP constants are case-sensitive by default.
Values to constants in PHP are assigned using the define()
function. Below we assign the value 3.141
to the constant PI
define('PI', 3.141);
and after defining it, we can use it throughout the program
echo PI; // prints 3.141
echo 'Circumference of a circle of radius 5 is', ' ', 2*PI*5; // 2πr
PHP Constants Cannot be Reassigned/Redefined
Once a constant is defined, we cannot reassign it to some other value with an =
operator as we do to variables. The below code will produce an error as we try to reassign PI
to a new value 3.141592
with an =
as we do to variables
<?php
define('PI', 3.141);
PI = 3.141592;
echo PI;
?>
PHP constants cannot be redefined either (unless you have runkit
extension installed). It will always take the first value it is assigned to. Below we redefine PI
to a new value 3.141592
. But upon printing PI
, we find that the value is that of the first value assigned to it
<?php
define('PI', 3.141);
define('PI', 3.141592);
echo PI; // 3.141
?>
Changing Case Sensitivity
The define()
function also has a third parameter (optional) for case-insensitivity, which is set to false
by default. If we set it to true
, we can use the constant in whatever letter case we please. Here we define a constant PI
, set the define()
function's case-insentivity parameter (the third parameter) to true
, and use it in varied cases
<?php
define('PI', 3.141, true);
echo pi; // 3.141
echo Pi; // 3.141
echo pI; // 3.141
?>
The const
Keyword
We can also use the language construct const
to define a constant
<?php
const PI = 3.141;
echo PI; // 3.141
?>
But const
defines constants at compile time, and so defining them conditonally (like inside if .. else
statements) will not work. And unlike constants defined by the define()
function, constants defined via the const
construct are always case-sensitive.