PHP Constants

Variables in a program are very important but you may also need some values which do not change or which cannot be reassigned a new value. Such element in  a PHP code are called PHP constants. The most important way to understand a constant is that it holds a single value throughout its lifecycle.

Unlike variables PHP constant do not require a $ symbol before their name. They are not declared with an assignment statement. PHP function define()  is used to declare a constant. Two arguments are required for declaring a constant.

  • The first argument is the name of the constant. By convention a constant is declared in uppercase to improve the readability of code and identification of constants  with in a script. The name of a constant cannot begin with a numeral. It can begin with a character, can contain underscore (_) any number of times. Like variable names PHP constant cannot include special characters.
  • The second argument is the value that you want the constant to hold. It can be an integer, floating point number, string, character or a Boolean value.

Declaration of PHP constants

A PHP constant is declared by calling the define() function  and passing on the name of constant and the value in the. Ensure that you declare a constant before using it. Unlike variable, a constant can only be used if it is declared beforehand.

define(SELECTED_OPTION, ‘All’)

define(COMM_PERCENT, 10)

define( BINARY_BASE,2)

define(CHECK, false)

Use of PHP Constants

Once a constant is declared it is ready to be used in the rest of the code. It can be used only after its declaration. You can never use a declared constant on the left hand side of an expression having assignment operator. The following assignment will generate an error


Wherever you use the constant name in a valid PHP expression, the constant name is replaced by the value assigned to it using define function.