Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

Listing 2.3 will print out a table with 10 rows. Each row will alternate background colors
between an intense green and a lighter green. I have used this technique in a project
where I pulled data from a database and separated rows with alternating blue and green
lines. Instead of using background colors, I chose between single-pixel images that I
stretched to span the browser window.


There is another way a variable can appear in a function's variable space: as an argument.
Functions are described in detail in Chapter 4, "Functions," but by now you have noticed
functions with variables inside their parentheses. Take another look at Listing 2.2. The
printCity function takes an argument called NameOfCity. When the function is called,
the variable is set with the value passed in the function call. In all other respects the
variable is the same as other local variables.


Assigning Values to Variables


The equal sign (=) is used to set the value of a variable. This is called the assignment
operator. On the left side of the assignment operator is a variable that will receive a value.
On the right side is an expression, which could be a simple string constant or a complex
combination of operators, variables, and constants.


When you assign a value to a variable, its type will change to fit the type of data you put
into it. This is in contrast to C, which tries to convert values to fit the type of the variable.
Assigning an integer to a variable that previously held a string converts the variable to an
integer.


Table 2.2. Examples of Variables Assignments
String Constants Integer Constants Double Constants
$myString = "leon"; $myInteger = 1; $myDouble = 123.456;
$myString = "\n"; $myInteger = -256; $myDouble = -98.76e5;


The simplest form of assignment is from a constant expression. This could be a number
or a string surrounded by quotes. Table 2.2 lists some examples.


By now you have probably noticed \n showing up in most of the examples. When a \
appears inside a string constant surrounded by double quotes, it has special meaning: Do
not print the next character. Instead the code stands for another character. This is so you
can override the special meaning of certain characters, or make certain characters more
visible. Strings surrounded by single quotes are treated literally. Any backslash codes are
ignored, except for escaping single quotes within the string. Table 2.3 lists some
backslash codes. The \n code stands for an end-of-line character.


Though it isn't strictly necessary, I use \n frequently. PHP allows you to create an entire
HTML page on a single line. This is acceptable to browsers, but it's very hard to debug

Free download pdf