PHP Constants

A constant, like a variable, is a name given to a particular area in memory that stores a value created by a PHP script, except that the value of a constant cannot be changed once it has been defined. Constants can be named using letters, numbers and underscores, and by default the name is case sensitive, however, this can be changed when the constant is defined using an optional parameter. Numbers cannot be used at the start of the name. Unlike variables, the scope of a constant is always global, so it is accessible throughout an entire PHP script. There is also no need to precede a constant name with a dollar sign when referencing it.

A constant can contain a string, integer, boolean or floating-point number, each of which can be defined as follows.

define('FIRST_NAME', 'Fred'); // String.
define('AGE_LIMIT', 30);      // Integer.
define('INCLUDE_VAT', TRUE);  // Boolean.
define('VAT', 20.0);          // Float.

Once defined, a constant can be used in a script, for example, to display its contents or used in some kind of calculation, if it contains an integer or floating-point number.


The above example would display the value of the 'FIRST_NAME' constant. As previously explained, constant names are case sensitive by default, so the below example would produce an error.

echo first_name;

This reference to the constant could be made valid by setting the optional case insensitive parameter in the constant definition to 'true'.

define('FIRST_NAME', 'Fred', true);