1.7. Using PHP Constants

PHP constants are similar to variables. Constants are given a name, and a value is stored in them. However, constants are constant; that is, they can't be changed by the script. After you set the value for a constant, it stays the same. If you used a constant for age and set it to 21, for example, it can't be changed.

Constants are used when a value is needed in several places in the script and doesn't change during the script. The value is set in a constant at the start of the script. By using a constant throughout the script, instead of a variable, you make sure that the value won't get changed accidentally. By giving it a name, you know what the information is instantly. And by setting a constant once at the start of the script (instead of using the value throughout the script), you can change the value of the constant in one place if needed instead of hunting for the value in many places in the script to change it.

For instance, you might set one constant that's the company name and another constant that's the company address and use them wherever needed. Then, if the company moves, you can just change the value in the company address constant at the start of the script instead of having to find and change every place in your script that echoed the company name.

You set constants by using the define statement. The format is

define("constantname","constantvalue");

For instance, to set a constant with the company name, use the following statement:

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.