Print this Section



A constant, like a variable, is a temporary in-memory placeholder that holds a value. Unlike variables, the value of a constant never changes. When a constant is declared, the define() function is used and requires the name of the constant and the value to be assigned to the constant. Constants can be assigned the following types of data:

  • Integers: Whole numbers or numbers without decimals. (e.g., 1, 999, 325812841)
  • Floating-point numbers (also known as floats or doubles): Numbers that contain decimals. (e.g., 1.11, 2.5, .44)
  • Strings: Text or numeric information. String data is always specified with quotes (e.g., "Hello World", "478-477-5555")

PHP constants unlike variables do not begin with the "$" sign. Constant names are usually uppercase. Constant names can contain letters, numbers, and the (_) underscore character. Constants cannot, however, begin with numbers. The following statements show how to declare constants.

   define("STRING_CONSTANT", "This is my string."); 
   define("NUMERIC_CONSTANT", 5); 

The first style of PHP tags is referred to as the XML tag style and is preferred most. This tag style works with eXtensible Markup Language (XML) documents. T his method should be used especially when mixing PHP with XML or HTML documents. The examples in this tutorial use this XML tag format.

Displaying Constants

The following code segment demonstrates how to declare a constant, assign the constant a value, and display the results in the browser window:

<!DOCTYPE html>
  <title>A Web Page</title>
       define("STRING_CONST", "My PHP program");
       define("INTEGER_CONST", 500);
       define("FLOAT_CONST", 2.25);

       echo STRING_CONST;
       echo INTEGER_CONST;
       echo FLOAT_CONST;

   My PHP program 

In the above example, three constants, STRING_CONST, INTEGER_CONST, and FLOAT_CONST, are declared and assigned values. Next, the echo statement is used to display the contents of the constants to the browser window. In addition to being echoed to the browser, constants can also be manipulated by using PHP's mathematical and string functions.

TOP | NEXT: Operators