PHP Constants
In PHP, constants are like variables, but once they are defined, they cannot be changed or undefined. They are typically used to store fixed values such as configuration settings, file paths, or magic numbers that shouldn’t be altered during execution.
Defining Constants
There are two main ways to define constants in PHP:
1. define()
function
-
Constant names are case-sensitive by default.
-
By passing
true
as the third parameter, you can make them case-insensitive:define("SITE_NAME", "My Website", true);
2. const
keyword (available from PHP 5.3)
-
const
must be used at the top-level scope (not inside functions, loops, or if statements). -
It is always case-sensitive.
Characteristics of Constants
-
They do not start with a
$
sign. -
They are global and can be accessed anywhere in the script.
-
Their value must be a scalar (int, float, string, or boolean) or an array (PHP 5.6+).
Magic Constants
PHP provides a set of predefined constants called magic constants that change depending on where they are used.
Some common ones: