learn

Constants

category: Basics
Created by: Dr.Ferrous

Constants

category: Basics
Created by: Dr.Ferrous
twitter google+ facebook pin 

Constants are similar to variables only in the sense that are used to store values, but otherwise, constants and variables differ in many ways.

To create a constant, it is used the define() function instead of the assignment operator (=):

The last parameter is case-insensitive and it's optional (a boolean value: true or false), and by default is false, meaning that the defined constant is in fact case-sensitive.

  • Constants do not use the initial dollar, their name must start with either a letter or an underscore character, followed by letters, numbers, or underscores.
  • By default and convention, a defined constant is uppercase, although this is not required.
  • A constant can only be assigned a scalar value (a string or a number). And unlike variables, a constant's value cannot be changed.
  • To access the value of a constant, make reference to its name.

The following example creates two constants and attempts to recreate one of them.

You cannot put the constant within quotation marks:

The scope of a defined constant is global, meaning it can be used in any defined function or class that is also part of that code file, including any other included files or functions.

If you want to check if a constant is defined, you can use the defined("CONSTANT") function. This function returns 1 if "CONSTANT" is defined, otherwise returns false.