Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

Creating PHP Code Blocks

PHP supports two kinds of comments: line comments and block

comments. A line comment automatically terminates at the end of

the line in which it is inserted. To create a line comment, add either

two forward slashes (//) or the pound symbol (#) before the text you

want to use as a comment. (You do not need to include both.) The //

or # characters instruct the scripting engine to ignore all text imme-

diately following the characters to the end of the line. You can place a

line comment either at the end of a line of code or on its own line.

Block comments allow multiple lines of comment text to be added.

You create a block comment by adding a forward slash and an asterisk

(/*) before the start of the text that you want included in the block,

and adding an asterisk and a forward slash (*/) after the last character

In the block. Any text or lines between the opening /* characters and

the closing */ characters are ignored by the PHP engine. The following

code shows a PHP code block containing line and block comments. If

a client requests a Web page containing the following script in a Web

browser, the scripting engine ignores the text marked with comments.

<?php

/*

This line is part of the block comment.

This line is also part of the block comment.

*/

echo "<h1>Comments Example</h1>"; // Line comment

// This line comment takes up an entire line.

# This is another way of creating a line comment.

/* This is another way of creating

a block comment. */

?>

Block

comments

cannot be

nested

inside other

block com-

ments. A block comment

stops at the first */,

regardless of how many

/* characters precede it.

Comments

created with

two slashes

(//) or the

/* and */

characters

are also used in C++,

Java, and JavaScript.

Comments created with

the pound symbol (#) are

used in Perl and shell

script programming.

21

To add comments to the PHP Environment Info Web page:

1.

Return to the MultipleScripts.php document in your text

editor.

Add the following block comment immediately after the first

opening PHP script delimiter:

/*

PHP code for Chapter 1.

The purpose of this code is to demonstrate how to

add multiple PHP code blocks to a Web page.

*/

2.

3.

Next, add the following line comments immediately after the

block comment, taking care to replace your name with your

first and last name and today’s date with the current date:

// your name

# today's date


CHAPTER 1

Getting Started with PHP

4.

Save the MultipleScripts.php document, upload it to the Web

server, and validate the document with the W3C XHTML

Validator. Open the document from your Web server to

ensure that the comments are not displayed.

Close your Web browser window.

5.

22

Short Quiz

1.

How many code declaration blocks can be inserted in a PHP

document?

Why does the PHP Group recommend that you use standard

PHP script delimiters to write PHP code declaration blocks?

What character or characters are used as delimiters to sepa-

rate multiple arguments (parameters) in a function declara-

tion or function call?

Describe the type of information that the phpinfo() function

generates.

Identify the two types of comments available in PHP and indi-

cate when each would be used.

2.

3.

4.

5.

Using Variables and Constants

One of the most important aspects of programming is the ability to

store values in computer memory and to manipulate those values.

These stored values are called variables. The values, or data, con-

tained in variables are classified into categories known as data types.

In this section, you will learn about PHP variables and data types, and

the operations that can be performed on them.

The values a program stores in computer memory are commonly

called variables. Technically speaking, though, a variable is actually a

specific location in the computer’s memory. Data stored in a specific

variable often changes. You can think of a variable as similar to a stor-

age locker—a program can put any value into it, and then retrieve the

value later for use in calculations. To use a variable in a program, you

first have to write a statement that creates the variable and assigns it a

name. For example, you can have a program that creates a variable to

store the current time. Each time the program runs, the current time

is different, so the value varies.

Using Variables and Constants

Programmers often talk about “assigning a value to a variable,” which

is the same as storing a value in a variable. For example, a shopping

cart program might include variables that store the current cus-

tomer’s name and purchase total. Each variable will contain different

values at different times, depending on the name of the customer and

the items the customer is purchasing.

23

Naming Variables

The name you assign to a variable is called an identifier. You must

observe the following rules and conventions when naming a variable:

• Identifiers must begin with a dollar sign (

$).

• Identifiers may contain uppercase and lowercase letters, numbers,

or underscores (_). The first character after the dollar sign must be

a letter.

• Identifiers cannot contain spaces.

• Identifiers are case sensitive.

One common practice is to use an underscore character to separate indi-

vidual words within a variable name, as in $my_variable_name.

Another option is to use initial capital letters for each word in a variable

name, as in $MyVariableName.

Unlike other types of PHP code, variable names are case sensitive.

Therefore, the variable named $MyVariable is completely different

from one named $Myvariable, $myVariable, or $MYVARIABLE. If

you receive an error when running a script, be sure that you are using

the correct case when referring to any variables in your code.

Declaring and Initializing Variables

Before you can use a variable in your code, you have to create it. The

process of specifying and creating a variable name is called declar-

ing the variable. The process of assigning a first value to a variable is

called initializing the variable. Some programming languages allow

you to first declare a variable without initializing it. However, in PHP,

you must declare and initialize a variable in the same statement, using

the following syntax:

$variable_name = value;

The equal sign in the preceding statement assigns an initial value to

(or initializes) the variable you created (or declared) with the name

$variable_name.

If you

attempt to

declare a

variable

without

initializing it,

you will receive an error.


CHAPTER 1

Getting Started with PHP

The value you assign to a variable can be a literal string, a numeric

value, or a Boolean value. For example, the following statement

assigns the literal string “Don” to the variable $MyName:

$MyName = "Don";

24

When you assign a literal string value to a variable, you must enclose

the text in single or double quotation marks, as shown in the preced-

ing statement. However, when you assign a numeric or Boolean value

to a variable, do not enclose the value in quotation marks or PHP will

treat the value as a string instead of a number. The following state-

ment assigns the numeric value 59 to the variable $RetirementAge:

$RetirementAge = 59;

In addition to assigning literal strings, numeric values, and Boolean

values to a variable, you can assign the value of one variable to

another. For instance, in the following code, the first statement

declares a variable named $SalesTotal and assigns it an initial value

of 0. (Remember that in PHP you must initialize a variable when

you first declare it.) The second statement creates another variable

named $CurOrder and assigns it a numeric value of 40. The third

statement then assigns the value of the $CurOrder variable (40) to the

$SalesTotal variable.

$SalesTotal = 0;

$CurOrder = 40;

$SalesTotal = $CurOrder;

Displaying Variables

To display a variable with the echo statement, you simply pass the

variable name to the echo statement, but without enclosing it in quo-

tation marks, as follows:

$VotingAge = 18;

echo $VotingAge;

If you want to display text strings and variables in the same statement,

you can pass them to the echo statement as individual arguments,

separated by commas. For example, the following code displays the

text shown in Figure 1-11. Notice that the text and elements are con-

tained within quotation marks, but the $VotingAge variable is not.

echo "<p>The legal voting age is ", $VotingAge, ".</p>";

Using Variables and Constants

25

Figure 1-11 Output from an echo statement

that is passed text and a variable

You can also include variable names inside a text string, although the

results you see on the screen depend on whether you use double or

single quotation marks around the text string that includes the vari-

able name. If you use double quotation marks, the value assigned to

the variable will appear. For example, the following statement displays

the same output that is shown in Figure 1-11:

echo "<p>The legal voting age is $VotingAge.</p>";

By contrast, if you use a variable name in a text string enclosed by

single quotation marks, the name of the variable will appear. For

example, the following statement displays the output shown in

Figure 1-12:

echo '<p>The legal voting age is $VotingAge.</p>';

Figure 1-12 Output of an echo statement that

includes text and a variable surrounded by single

quotation marks

Modifying Variables

You can modify the variable’s value at any point in a script. The fol-

lowing code declares a variable named $SalesTotal, assigns it an

initial value of 40, and displays it using an echo statement. The third

statement changes the value of the $SalesTotal variable and the

fourth statement displays the new value. Figure 1-13 shows the out-

put in a Web browser.

CHAPTER 1

The two

adjacent

dollar signs

are not

special

syntax. The

first dollar sign, because

it is not immediately

followed by a variable

name, is treated as a

literal dollar sign charac-

ter and displayed on the

page. The second dollar

sign and the variable

name that follows it are

treated as an identifier,

and the value of the

identifier is displayed

on the page.

Getting Started with PHP

$SalesTotal =

echo "<p>Your

$SalesTotal =

echo "<p>Your

40;

sales total is $$SalesTotal</p>";

50;

new sales total is $$SalesTotal</p>";

26

Figure 1-13

Results of a script that includes a changing variable

It’s an old tradition among programmers to practice a new language

by writing a script that prints or displays the text “Hello World!”. If

you are an experienced programmer, you have undoubtedly created

“Hello World” programs in the past. If you are new to programming,

you will probably create “Hello World” programs as you learn pro-

gramming languages. Next, you will create your own “Hello World”

program in PHP. You will create a simple script that displays the text

“Hello World!”, says “Hello” to the sun and the moon, and displays a

line of scientific information about each celestial body. You will use

variables to store and display each piece of information.

To create the “Hello World” program:

1.

2.

Create a new document in your text editor.

Type the <!DOCTYPE> declaration, <html> element, header

information, and <body> element. Use the strict DTD and

“Hello World” as the content of the

<title> element. Your

document should appear as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>

<title>Hello World</title>

</head>

<body>

</body>

</html>

3.

Add the following standard PHP script delimiters to the docu-

ment body:

<?php

?>


Using Variables and Constants

4.

In the code block, type the following statements to declare the

variables containing the names of each celestial body, along

with variables containing scientific information about each

celestial body:

$WorldVar = "World";

$SunVar = "Sun";

$MoonVar = "Moon";

$WorldInfo = 92897000;

$SunInfo = 72000000;

$MoonInfo = 3456;

27

5.

Add the following statements to the end of the script sec-

tion to display the values stored in each of the variables you

declared and initialized in the last step:

echo "<p>Hello $WorldVar!<br />";

echo "The $WorldVar is $WorldInfo miles from the

$SunVar.<br />";

echo "Hello ", $SunVar, "!<br />";

echo "The $SunVar's core temperature is

approximately $SunInfo

degrees Fahrenheit.<br />";

echo "Hello ", $MoonVar, "!<br />";

echo "The $MoonVar is $MoonInfo miles in

diameter.</p>";

6.

Save the document as HelloWorld.php in the Chapter direc-

tory for Chapter 1. After you save and upload the document,

validate it with the W3C XHTML Validator.

Open the HelloWorld.php file in your Web browser by enter-

ing the following URL: http://<yourserver>/PHP_Projects/

Chapter.01/Chapter/HelloWorld.php. You should see the

Web page in Figure 1-14.

7.

If you

receive error

messages,

make sure

that you

typed all the

variables in the correct

case. (Remember that

variables in PHP are case

sensitive.)

Figure 1-14

8.

Output of HelloWorld.php

Close your Web browser window.


CHAPTER 1

Getting Started with PHP

Defining Constants

A constant contains information that does not change during the

course of program execution. You can think of a constant as a vari-

able with a static value. A common example of a constant is the value

of pi (π), which represents the ratio of the circumference of a circle to

its diameter. The value of pi never changes from a constant value of

approximately 3.141592.

Unlike variable names, constant names do not begin with a dollar

sign ($). In addition, it is common practice to use all uppercase letters

for constant names. When you create a constant, you do not declare

and initialize it the way you declare a variable. Instead, you use the

define() function to create a constant. The syntax for the define()

function is as follows:

define("CONSTANT_NAME", value);

28

The value you pass to the define() function can be a text string, num-

ber, or Boolean value. In the following example, the first constant def-

inition passes a text string to the define() function while the second

constant definition passes a number:

define("DEFAULT_LANGUAGE", "Navajo");

define("VOTING_AGE", 18);

Remember

that you

cannot

change the

value of a

constant

after you define it in your

program. If you attempt

to use the define()

function to change the

value of an existing

constant, you will receive

an error.

By default, constant names are case sensitive, as are variables.

However, you can make constant names case insensitive by passing a

Boolean value of TRUE as a third argument to the define() function, as

follows:

define("DEFAULT_LANGUAGE", "Navajo", TRUE);

With the preceding statement, you can refer to the

DEFAULT_LANGUAGE constant using any letter case, including

default_language or Default_Language. However, standard

programming convention is to use all uppercase letters for con-

stant names, so you should avoid making your constant names case

insensitive.

When you refer to a constant in code, remember not to include a dol-

lar sign, as you would with variable names. You can pass a constant

name to the echo statement in the same manner as you pass a vari-

able name (but without the dollar sign), as follows:

echo "<p>The legal voting age is ", VOTING_AGE, ".</p>";

The preceding statement displays the text “The legal voting age is 18.”

in the Web browser. Unlike variables, you cannot include the constant

name within the quotation marks that surround a text string. If you

do, PHP treats the constant name as ordinary text that is part of the


Using Variables and Constants

string. For example, consider the following statement, which includes

the constant name within the quotation marks that surround the text

string:

echo "<p>The legal voting age is VOTING_AGE.</p>";

Instead of displaying the value of the constant (18), the preceding

statement displays “The legal voting age is VOTING_AGE.” in the

Web browser.

To replace the $WorldInfo, $SunInfo, and $MoonInfo variables in

the HelloWorld.php script with constants:

1.

2.

PHP includes

numerous

predefined

constants that

you can use in

your scripts.

29

Return to the HelloWorld.php document in your text editor.

Replace the $WorldInfo, $SunInfo, and $MoonInfo variable

declarations with the following constant definitions:

define("WORLD_INFO", 92897000);

define("SUN_INFO", 72000000);

define("MOON_INFO", 3456);

3.

Replace the $WorldInfo, $SunInfo, and $MoonInfo variable

references in the echo statements with the new constants. The

modified echo statements should appear as follows:

echo "<p>Hello ", $WorldVar, "!<br />";

echo "The $WorldVar is ", WORLD_INFO,

" miles from the $SunVar.<br />";

echo "Hello ", $SunVar, "!<br />";

echo "The $SunVar's core temperature is

approximately ",

SUN_INFO, " degrees Fahrenheit.<br />";

echo "Hello ", $MoonVar, "!<br />";

echo "The $MoonVar is ", MOON_INFO, " miles in

diameter.</p>";

4.

Save and upload the HelloWorld.php document and then vali-

date it with the W3C XHTML Validator.

Open the HelloWorld.php document from your Web server.

The Web page should look the same as it did before you

added the constant declarations.

Close your Web browser window.

5.

6.

Short Quiz

1.

Describe the two-step process of making a variable available

for use in the PHP script.


CHAPTER 1

Getting Started with PHP

2.

Explain the syntax for displaying a variable or variables in the

PHP script using the echo or print statements.

How do you make a constant name case insensitive?

3.

30

Working with Data Types

PHP also

supports a

“resource”

data type,

which is a

special vari-

able that holds a refer-

ence to an external

resource, such as a data-

base or XML file.

The term

NULL refers

to a data type

as well as a

value that can

be assigned to a variable.

Assigning the value NULL

to a variable indicates

that the variable does not

contain a usable value. A

variable with a value of

NULL has a value

assigned to it—null is

really the value “no

value.” You assign the

NULL value to a variable

when you want to ensure

that the variable does not

contain any data. For

instance, with the

$SalesTotal variable

you saw earlier, you may

want to ensure that the

variable does not contain

any data before you use

it to create another pur-

chase order.

Variables can contain many different kinds of values—for example,

the time of day, a dollar amount, or a person’s name. A data type

is the specific category of information that a variable contains. The

concept of data types is often difficult for beginning programmers to

grasp because in real life you don’t often distinguish among different

types of information. If someone asks you for your name, your age, or

the current time, you don’t usually stop to consider that your name

is a text string and that your age and the current time are numbers.

However, a variable’s specific data type is very important in program-

ming because the data type helps determine the manner in which the

value is stored and how much memory the computer allocates for the

data stored in the variable. The data type also governs the kinds of

operations that can be performed on a variable.

Data types that can be assigned only a single value are called primi-

tive types. PHP supports the five primitive data types described in

Table 1-1.

Data Type

Integer numbers

Floating-point

numbers

Boolean

String

NULL

Table 1-1

Description

The set of all positive and negative numbers and

zero, with no decimal places

Positive or negative numbers with decimal places or

numbers written using exponential notation

A logical value of “true” or “false”

Text such as “Hello World”

An empty value, also referred to as a NULL value

Primitive PHP data types

The PHP language also supports reference, or composite, data types,

which can contain multiple values or complex types of information,

as opposed to the single values stored in primitive data types. The two

reference data types supported by the PHP language are arrays and

objects. In this chapter, you will study basic array techniques. You will

learn about advanced arrays and objects in later chapters.


Working with Data Types

Many programming languages require that you declare the type of

data that a variable contains. Such programming languages are called

strongly typed programming languages. Strong typing is also

known as static typing because the data type for a variable will not

change after it has been declared. Programming languages that do not

require you to declare the data types of variables are called loosely

typed programming languages. Loose typing is also known as

dynamic typing because the data type for a variable can change after

it has been declared. PHP is a loosely typed programming language.

In PHP, you are not required to declare the data type of variables,

and, in fact, you are not allowed to do so. Instead, the PHP scripting

engine automatically determines what type of data is stored in a vari-

able and assigns the variable’s data type accordingly. The following

code demonstrates how a variable’s data type changes automatically

each time the variable is assigned a new literal value.

$ChangingVariable = "Hello World"; // String

$ChangingVariable = 8;// Integer number

$ChangingVariable = 5.367;// Floating-point

// number

$ChangingVariable = TRUE;// Boolean

$ChangingVariable = NULL;// NULL

31

Although you

cannot

declare a data

type when you

first create a

variable, you can force a

variable to be converted

to a specific type. You

learn how to force a vari-

able to be a specific type

at the end of this section.

Strictly

speaking,

there are dif-

ferences

between the

terms “strong typing” and

“static typing,” and

between “loose typing”

and “dynamic typing.”

The specifics of these

differences are beyond

the scope of this book.

The terms “strongly

typed” and “loosely

typed” are used here in

the generic sense, not in

the technical sense.

The next two sections focus on two commonly used data types:

numeric and Boolean.

Numeric Data Types

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]