Validate Drop-Downs, Radio Buttons, and Check Boxes in the PHP
Check Whether PHP Cookies Are Enabled
The Basics of Writing PHP Code

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, the value is always and forever 21.

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


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

define("COMPANY","My Fine Company");

Use the constant in your script wherever you need your company name:


When you echo a constant, you can’t enclose it in quotes. If you do, you echo the constant name, instead of the value. You can echo it without anything, as shown in the preceding example, or enclosed in parentheses.

You can use any name for a constant that you can use for a variable, as long as you follow these conventions:

  • No identifier: Constant names are not preceded by a dollar sign ($).

  • Case: By convention, constants are given names that are all uppercase, so you can easily spot constants, but PHP itself doesn’t care what you name a constant. You don't have to use uppercase; it's just clearer.

  • Characters: You can store either a string or a number in it. The following statement is perfectly okay with PHP:

define ("AGE",29);
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Create Relationships between MySQL Tables
How to Identify What MySQL Accounts Currently Exist
Design a Sample MySQL Database
How to Handle MySQL Errors
How to Send an SQL Server to the MySQL Server