- Before You Begin: Accessing PHP
- Creating a Sample Application: Bob's Auto Parts
- Embedding PHP in HTML
- Adding Dynamic Content
- Accessing Form Variables
- Understanding Identifiers
- Examining Variable Types
- Declaring and Using Constants
- Understanding Variable Scope
- Using Operators
- Working Out the Form Totals
- Understanding Precedence and Associativity
- Using Variable Handling Functions
- Making Decisions with Conditionals
- Repeating Actions Through Iteration
- Breaking Out of a Control Structure or Script
- Employing Alternative Control Structure Syntax
- Using declare
Declaring and Using Constants
As you saw previously, you can readily change the value stored in a variable. You can also declare constants. A constant stores a value just like a variable, but its value is set once and then cannot be changed elsewhere in the script.
In the sample application, you might store the prices for each item on sale as a constant. You can define these constants using the define function:
Now add these lines of code to your script. You now have three constants that can be used to calculate the total of the customer’s order.
Notice that the names of the constants appear in uppercase. This convention, borrowed from C, makes it easy to distinguish between variables and constants at a glance. Following this convention is not required but will make your code easier to read and maintain.
One important difference between constants and variables is that when you refer to a constant, it does not have a dollar sign in front of it. If you want to use the value of a constant, use its name only. For example, to use one of the constants just created, you could type
As well as the constants you define, PHP sets a large number of its own. An easy way to obtain an overview of them is to run the phpinfo() function:
This function provides a list of PHP’s predefined variables and constants, among other useful information. We will discuss some of them as we go along.
One other difference between variables and constants is that constants can store only boolean, integer, float, or string data. These types are collectively known as scalar values.