The PHP Constant

The PHP Constant
The PHP constant is very similar to a PHP variable in that it is used to store a value but, unlike a variable, the value cannot be changed. It is called a constant because; you guessed it, it stays constant throughout the PHP program. By using a constant you "lock in" the value which prevents you from accidentally changing it.

Secondly, if you want to run a program several times using a different value each time, you do not need to search throughout the entire program and change the value at each instance. You only need to change it at the beginning of the program where you set the initial value for the constant.

Let's take a look at an example where we use the define function to set the initial value of a constant to the state in the US that a business is located in. Then we can use this constant in an accounting program.

define("CONSTANT_NAME", "value");

define("STATE", "Ohio");

echo STATE;

In the example above, the define function begins with the function name define followed by parenthesis. Within the parenthesis are the name of the constant and the value to be assigned to the constant. Both are enclosed within quotation marks and separated by a comma. This is all followed by a semicolon.
  • You will notice that the value of Ohio is placed within quotation marks. This is because it is a character string. To store a numeric value you do not need quotation marks.

    define("TAX", 4);

  • You will also notice that, unlike PHP variables, there is no $ in front of the constant name.

  • Although it is not required, most programmers use all uppercase letters when naming constants to make them stand out from the variables in their program.

  • You do not use quotation marks when you use a constant in an echo statement. If you do, the echo statement will display the constant name.

    echo STATE; // will display Ohio

    echo "STATE"; // will display STATE






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.