[ Team LiB ] Previous Section Next Section

Variables

A variable is a special container you can define to hold a value. Variables are fundamental to programming. Without them, you'd be forced to hard-code all the values in your scripts. In adding two numbers together and printing the result, we have achieved something useful:


print (2 + 4);

This script is useful only for people who want to know the sum of 2 and 4, however. To get around this, we could write a script for finding the sum of another set of numbers, say 3 and 5. This approach to programming is clearly absurd. Variables enable you to create templates for operations (adding two numbers, for example) without worrying about what values the variables contain. The variables are given values when the script is run, possibly through user input or a database query.

You should use a variable whenever the data that is being subjected to an operation in your script is liable to change from one script execution to another, or even within the lifetime of the script itself.

A variable consists of a name that you can choose, preceded by a dollar ($) sign. The variable name can include letters, numbers, and the underscore character (_). Variable names cannot include spaces or characters that are not alphanumeric, and they should begin with a letter or an underscore. The following code defines some legal variables:


$a;
$a_longish_variable_name;
$_2453;
$sleepyZZZZ;

Remember that a semicolon (;) is used to end a PHP statement. The semicolons in the previous fragment of code are not part of the variable names.

A variable is a holder for a type of data. It can hold numbers, strings of characters, objects, arrays, or booleans. The contents of a variable can be changed at any time.

As you can see, you have plenty of choices about naming. To declare a variable, you need only to include it in your script. You usually declare a variable and assign a value to it in the same statement, like so:


$num1 = 8;
$num2 = 23;

The preceding lines declare two variables, using the assignment operator (=) to give them values. You will learn about assignment in more detail in the section "Operators and Expressions," later in the hour. After you give your variables values, you can treat them exactly as if they were the values themselves. In other words


print $num1;

is equivalent to


print 8;

as long as $num1 contains 8.

    [ Team LiB ] Previous Section Next Section