PHP Constants

PHP constants are similar to variables. Constants are given a name, and a value is stored in them. However, they can’t be changed by the script. After you set the value for a constant, it stays the same. For example, if you used a constant for age and set it to 21, the value is always and forever 21.

Constants are used when a value is needed in several places in the script and doesn’t change during the script. The value is set in a constant at the start of the script. By using a constant throughout the script, instead of a variable, you make sure that the value won’t get changed accidentally.

For example, you might set one constant that’s the company name and another constant that’s the company address and use them wherever needed. Creating a constant is done by calling the define(), and passing a string of your constant’s name and its contents.

define("CONSTANTNAME","Constant Value");

For example, to set a constant with the company name, use the following statement:

define("COMPANY","My New Company");

You can use any name for a constant that you can use for a variable, as long as you follow these conventions:

  • No identifier: Constant names are not preceded by a dollar sign ($).
  • Case: By convention, constants are given names that are all uppercase, so you can easily spot constants, but PHP itself doesn’t care what you name a constant.
  • Characters: You can store either a string or a number in it.