PHP Constants

Suppose we have a variable that should not change its value in all project, we can define a variable for it, but it is not correct , because we can change it by accident in project. For it, Php have constants.

Constants is the named of a value that does not change during the execution of the program.

In order to create a constant we use define() function, in the following format.

  define (name, value, caseSensitive)


name - is a name of constant, which must comply with the same rules as the other names in PHP .

value - value of constant.

caseSensitive - Optional parameter, it specifies whether the constant name should be case-insensitive (true) or not (false).

   define("pi", 3.14, true);
   // output 3.14

   echo (PI);
   // output 3.14


Constants are like variables except.

  • Constants have not $ sign
  • Constants can be defined only by using the define () function, instead of assigning values
  • Constants can be defined and accessed anywhere in project, which means that they are automatically global
  • Constants cannot change value, after defining

  Be careful, with the name of constants, __NAME__, is valid name for constant, but php have some Magic Constants, that is like __constantName__ syntax, and if one day php provides a magical constant __NAME__ that will break your script.

About magical constants we will talk later.