PHP Tutorials

Variables and Constants

Now that you know the basics of creating a PHP program, it’s time to learn about all the things a program can do. Essentially, all programs exchange and manipulate data. For example, the information from a Web site’s feedback form might be collected and sent via e-mail to the Webmaster. The data from the form would be stored in variables, which could then be used to send the form data in an e-mail.

Thus, you have seen one basic use for variables and constants. Any data that a program works with is stored in variables and constants. So, as we explore the way your program will work with data in this chapter and the chapters ahead, we’ll start with variables and constants, the storage units for all data.

This chapter teaches you the following:

How to declare variables and constants

Naming techniques

Types and type casting

Scope

References

Filed under: Chapter 2 @ 8:38 pm

Introduction to Variables and Constants

A program contains two basic things: commands and values. The commands all have certain tasks they perform; the values are the information that the tasks are performed with. Until now, all your programs have used literal values; that is, any time a value has been specified, it has been hard coded into the program.

For example, take a look at an echo statement found in Chapter 1, “Welcome to PHP”:



echo "World!";

This statement performs the echo command (which we know inserts text) using the literal value given after it (”World!”).

NOTE

A literal is a value that you give explicitly within a program. For example, 5, 5.5, and “World!” are all literals.

The point of a program isn’t to say “World!” all the time. That could be accomplished with a regular HTML page. The whole point of writing a program is to have a uniform task performed with whatever information is specified. For example, you might want it to be able to say “Earth” instead of “World.”

Let’s consider what you’re planning to do. You know the program should output something, either way. Thus, you know you want the program to do something like this:

echo something;

You just don’t know what something is. To specify what something is, use a variable. A variable is a name that represents a value. The value of a variable may change throughout a program, or it may stay the same once it’s set.

For example, you might use a variable called $strText to insert whatever text is being used for a particular execution of the program.

NOTE

The name $strText is preceded by a dollar sign because that’s how PHP recognizes it as a variable.

Also, if you’re curious, the str prefix is an abbreviation for “string” (the type of data will be character string); it’s purpose is a matter of style, only.

Don’t worry about it right now; we’ll discuss data types and style conventions related to variables later in this chapter.

The following program uses the variable $strText, instead of a literal:





TIP

For now, don't be too distracted by the line that says:

$strText = $HTTP_GET_VARS['strText'];

This statement takes whatever value is specified in the URL and stores it in $strText; since it’s more related to program input, we won’t discuss it further until Chapter 3, “Program Input and Output (I/O).”

Try running this program with the following URLs (replacing www.example.com/path/ with the appropriate address for this program):

http://www.example.com/path/ch02ex01.php?strText=World

http://www.example.com/path/ch02ex01.php?strText=Earth

http://www.example.com/path/ch02ex01.php?strText=PHP%20Programmer

The output changes each time you run the program, depending on what URL you specify. Although this program is very basic, it shows the definite usefulness of variables.

TIP

The URLs shown aren’t as complex as they might seem; we’ll pick these apart and discuss them in Chapter 3. For now, notice that in each URL, a different value is specified for strText, and when you enter each URL, the program displays the corresponding value.

It is important to note that although variables and constants serve the same purpose, they aren’t at all identical.

Whereas, the value of a variable might change any number of times throughout the execution of a program, constants are values that will never change (and in fact can’t change) during the execution of the program.

Constants are often used to set program options. For instance, a constant named DEBUG might be used to determine how much information should be given to the visitor if something goes wrong—either a simple error message to tell the visitor there’s a problem or a detailed error message to help the programmer resolve problems within the script.

Filed under: Chapter 2 @ 8:37 pm

Declaration and Assignment

Declaration is the term used to describe the creation of a variable or constant. Assignment, which is covered in the following sections, is the process of storing a value in a variable.

Declaring Variables
Declaring a variable is quite simple—all you have to do is assign something to it. If, for example, you wish to assign the number five to a variable named $intFive, you would use the following:



$intFive = 5;

The dollar sign in the variable name isn’t part of the variable name, per se. Instead, it’s how PHP knows you’re referring to a variable named intFive. Whenever you use a variable, you must precede it with a dollar sign.

Variable names in PHP must follow the following requirements:

Any combination of letters, numbers, and underscores can be used.

Names can be as short as one character and can be of any length.

Names can begin only with a letter or an underscore; variable names cannot begin with a number.

As you already know, just because PHP understands a variable following the requirements seen previously doesn’t mean you and the people who read your code will. To improve style, variables should be named according to these style guidelines:

Keep variable names meaningful. For example, don’t use $x to store a visitor’s age; instead, use $intVisitor_age.

If you come back to make changes or fixes in your program a month from when you first write it, you will be confused with variable names like $x because $x doesn’t mean anything, whereas $intVisitor_age says exactly what it contains.

Variable names should be reasonably short. Typing a 25-character variable name just a few times will become a bit tedious and frustrating. Try abbreviating; just be sure your abbreviation makes sense.

For example, instead of $strWebPageFormFieldForEmailAddress, it would obviously be just as clear if it were named $strVisitor_Email.

Prefix a variable type abbreviation to the variable name. Although variable types are explained a little later in the chapter, you should recognize now that the variables suggested so far in this list have been preceded by int or str.

All variables should be prefixed as follows: int for integers, flt or dbl for floating-point numbers or doubles, str for strings, and arr for arrays.

Format your variable names in a hierarchical fashion, separating major divisions with underscores. For example, if you have a visitor’s first name, last name, and e-mail address, it’s better to use $strVisitor_first, $strVisitor_last, and $strVisitor_email instead of $strFirstName, $strLastName, and $strEmail because you may find later in the script that you want to refer to another e-mail address or another person’s name. Although the underscore-divided names are a little bit longer, it’s worth it to keep conflicts and confusion from arising later in the script. You don’t want to find yourself asking, “Whose e-mail do I have in $strEmail?”

Following these conventions makes your programs easier to understand to anyone that has to work with them, especially you.

Assigning Variables
There are two ways a variable can be assigned: in the script itself, or by the PHP interpreter. For now, let’s focus on variables that are created (declared and assigned) by the script itself. Variables assigned automatically by the PHP interpreter (such as the $HTTP_GET_VARS variable found in the first example of this chapter), will be discussed in Chapter 3.

Assignment, as you’ve already learned, occurs when a value is stored in a variable. Whenever you assign a value to a variable, you must keep in mind the order in which the assignment will be processed. For example, the following two statements are not equivalent:



$intFive = 5;
5 = $intFive;

As a rule of thumb, read assignments from right to left—the first would read, “the number 5 should be assigned to the variable $intFive.” Reading assignments in this fashion will become more and more important as your programs and statements grow in complexity.

Now, take a look at the second assignment—”the variable $intFive should be assigned to the number 5.” The latter doesn’t make sense; it will definitely not work. In fact, if you were to use this statement in a program, PHP would stop with a parse error.

Declaring a Constant
Declaring a constant is done using the define function (more will be discussed about functions in Chapter 11, “Classes and Objects”). The following example demonstrates the declaration of a constant, EXAMPLE, with a value of 5:





Notice that EXAMPLE is not preceded by a dollar sign in either statement. The dollar sign is reserved for use only with variables; constants should never be preceded by a dollar sign.

Just as variables have naming requirements that must be followed, so do constants. The following guidelines will ensure that you always use a valid name for a constant:

A constant’s name should not be preceded by a dollar sign.

The name should begin with a letter or underscore, but never a number.

Constants cannot be redefined; that is, the value of EXAMPLE cannot be changed after it has already been defined. After all, that’s why it’s defined as a constant instead of a variable.

As with variables, constants should also be subject to naming conventions for clarity and good style. Adhered to consistently, the following guidelines improve the style of your code:

Keep names short enough to be convenient. This rule is followed less strictly than most; because constants are generally only used for setting options, they aren’t usually mentioned as frequently as variables. Therefore, it’s generally acceptable to make a constant’s name longer.

Constants should always be named using all uppercase. This helps distinguish that you’re intentionally using the word without quotes. Thus, as soon as you see a word in your program written in all caps, you know you can probably look for a constant being defined with that name.

Separate words with underscores. Since constants don’t have the ability to switch case (capitalizing the first letter of every word and using lowercase for the rest), underscores are necessary to keep the separate words in a name easily distinguishable.

Name constants in a hierarchical fashion. As with variables, if you have several constants that are related in some way (they all describe the program, for instance), it would be good to prefix them with PROGRAM. Thus, you’ll end up with PROGRAM_VERSION, PROGRAM_AUTHOR, and PROGRAM_LAST_UPDATE, which are a lot less ambiguous than VERSION, AUTHOR, and LAST_UPDATE, which could describe a number of different things.

Also, by using a hierarchical form (as opposed to just separating words, which would lead to names like PROGRAM_VERSION and LAST_PROGRAM_UPDATE), the constants are grouped into a related set. Because they all begin with PROGRAM_, we know they’re related. If, however, we used a name such as LAST_PROGRAM_UPDATE, although it is clear, we don’t know just from looking at it that it is related to the other two constants.

NOTE

Although a variable type prefix is very useful in variables, it isn’t necessary in constants. The purpose and type of a constant never change (and can’t change), so it’s safe to assume that a variable is whatever type it is defined to be when it’s first defined.

TIP

It’s a good idea to define all constants at the beginning of your program. If you get halfway through and need to define another constant, scroll back up and put it at the top of the file instead of just putting it wherever you currently are in the program. This will make it much easier to find out what the value of the constant is; looking through hundreds of lines of code in multiple files is quite a task if constants aren’t defined at the top of the program.

Deciding Whether to Use a Variable or Constant
If you find wondering whether to use a variable or a constant, think about how the information will be needed within the program.

If the value might be modified sometime during the program’s execution, always use a variable. Using a constant completely prevents the value being modified.

Conversely, if you want to intentionally keep a value from being modified, use a constant. This is a built-in feature of the language so you can protect certain values from accidentally being changed, either by you or by another programmer who isn’t as familiar with your program.

If you’re not sure whether to use a variable or a constant, use a variable. If you use a variable where a constant might have been a better choice, it’s not really a big problem; however, if you use a constant where a variable would have been better, changing it to a variable throughout the script can give you quite a headache.

Related:

More PHP Tutorials

Filed under: Chapter 2 @ 10:17 pm
Next Page »

Powered by WordPress