PHP Constants

A constant, like a variable, is a temporary placeholder in memory 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 you want to give the constant.

Constants can be assigned the following types of data:

Integers - whole numbers or numbers without decimals. (1, 999, 325812841)

Floating-point numbers (also known as floats or doubles) - Numbers that contain decimals. (1.11, 2.5, .44)

Strings - text or numeric information. String data is always specified with quotes ("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. Declaring constants is demonstrated below:

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

define("NUMERIC_CONSTANT", 5);

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 PUBLIC "-//W3C//DTD/XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml11-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>A Web Page</title>
</head>
<body>

<p>

<?php 

define("STRING_CONST","My PHP program");
define("INTEGER_CONST",500);
define("FLOAT_CONST",2.25);


echo STRING_CONST;
echo INTEGER_CONST;
echo FLOAT_CONST;

?>

</p>
</body>
</html>

My PHP program
500
2.25

In this 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 using PHP's mathematical and string functions.