1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Kỹ thuật lập trình >

Hour 5. Flow Control Functions in PHP

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.37 MB, 561 trang )


This document is created with the unregistered version of CHM2PDF Pilot



[ Team LiB ]



This document is created with the unregistered version of CHM2PDF Pilot



Switching Flow

Most scripts evaluate conditions and change their behavior accordingly. The capability to make decisions makes your

PHP pages dynamic, able to change their output according to circumstances. Like most programming languages,

PHP allows you to do this with an if statement.



The if Statement

An if statement is a way of controlling the execution of a statement that follows it (that is, a single statement or a block

of code inside braces). The if statement evaluates an expression between parentheses. If this expression results in a

true value, the statement is executed. Otherwise, the statement is skipped entirely. This enables scripts to make

decisions based on any number of factors:

if ( expression ) {

// code to execute if the expression evaluates to true

}



Listing 5.1 executes a block of code only if a variable contains the string "happy".

Listing 5.1 An if Statement

1:

2:

3:

4:

5:

6:

7:

8:

9:

10:

11:

12:

13:







Listing 5.1






$mood = "happy";

if ( $mood == "happy" ) {

print "Hooray, I'm in a good mood";

}

?>







You use the comparison operator == to compare the variable $mood with the string "happy". If they match, the

expression evaluates to true, and the code block below the if statement is executed.



Put these lines into a text file called testif.php, and place this file in your Web server document root. When you

access this script through your Web browser, it produces the following:

Hooray, I'm in a good mood



If you change the value of $mood to "sad" and run the script, the expression in the if statement evaluates to false, and

the code block is skipped. The script remains silent.



Using the else Clause with the if Statement

When working with the if statement, you will often want to define an alternative block of code that should be

executed if the expression you are testing evaluates to false. You can do this by adding else to the if statement



This document is created with the unregistered version of CHM2PDF Pilot



[ Team LiB ]



This document is created with the unregistered version of CHM2PDF Pilot



[ Team LiB ]



This document is created with the unregistered version of CHM2PDF Pilot



Loops

So far we've looked at decisions that a script can make about what code to execute. Scripts can also decide how

many times to execute a block of code. Loop statements are designed to enable you to achieve repetitive tasks.

Almost without exception, a loop continues to operate until a condition is achieved, or you explicitly choose to exit

the loop.



The while Statement

The while statement looks similar in structure to a basic if statement:

while ( expression ) {

// do something

}



As long as a while statement's expression evaluates to true, the code block is executed over and over again. Each

execution of the code block in a loop is called an iteration. Within the block, you usually change something that

affects the while statement's expression; otherwise, your loop continues indefinitely. Listing 5.6 creates a while loop

that calculates and prints multiples of 2 up to 24.

Listing 5.6 A while Statement

1:

2:

3:

4:

5:

6:

7:

8:

9:

10:

11:

12:

13:

14:







Listing 5.6






$counter = 1;

while ( $counter <= 12 ) {

print "$counter times 2 is ".($counter*2)."
";

$counter++;

}

?>







In this example, we initialize a variable $counter in line 7. The while statement in line 8 tests the $counter variable. As

long as the integer that $counter contains is less than or equal to 12, the loop continues to run. Within the while

statement's code block, the value contained by $counter is multiplied by two, and the result is printed to the browser.

Then line 10 increments $counter. This last stage is extremely important. If you were to forget to change $counter,

the while expression would never resolve to false, and the loop would never end.



Put these lines into a text file called testwhile.php, and place this file in your Web server document root. When you

access this script through your Web browser, it produces the following:

1

2

3

4

5

6

7

8



times

times

times

times

times

times

times

times



2

2

2

2

2

2

2

2



is

is

is

is

is

is

is

is



2

4

6

8

10

12

14

16



This document is created with the unregistered version of CHM2PDF Pilot



[ Team LiB ]



This document is created with the unregistered version of CHM2PDF Pilot



[ Team LiB ]



This document is created with the unregistered version of CHM2PDF Pilot



Code Blocks and Browser Output

In Hour 3, "Installing and Configuring PHP,"you learned that you can slip in and out of HTML mode at will, using the

PHP start and end tags. In this hour, you have discovered that you can present distinct output to the user according

to a decision-making process that we can control with if and switch statements. In this section, we will combine these

two techniques.



Imagine a script that outputs a table of values only when a variable is set to the Boolean value true. Listing 5.13

shows a simplified HTML table constructed with the code block of an if statement.

Listing 5.13 A Code Block Containing Multiple print() Statements

1:

2:

3:

4:

5:

6:

7:

8:

9:

10:

11:

12:

13:

14:

15:

16:

17:

18:







Listing 5.13






$display_prices = true;

if ( $display_prices ) {

print "

";

print "";

print "";

print "
";

print "today's prices in dollars";

print "
143271
";

}

?>







If $display_prices is set to true in line 7, the table is printed. For the sake of readability, we split the output into

multiple print() statements, and once again escape any quotation marks.



Put these lines into a text file called testmultiprint.php, and place this file in your Web server document root. When

you access this script through your Web browser, it should look like Figure 5.2.



Figure 5.2. Output of Listing 5.13.



This document is created with the unregistered version of CHM2PDF Pilot



[ Team LiB ]



This document is created with the unregistered version of CHM2PDF Pilot



[ Team LiB ]



Summary

In this hour, you learned about control structures and the ways in which they can help to make your scripts flexible

and dynamic. Most of these structures will reappear regularly throughout the rest of the book.



You learned how to define an if statement and how to provide for alternative actions with the elseif and else clauses.

You learned how to use the switch statement to change flow according to multiple equivalence tests on the result of

an expression. You learned about loops—in particular, the while and for statements—and you learned how to use

break and continue to prematurely end the execution of a loop or to skip an iteration. You learned how to nest one

loop within another and saw a typical use for this structure. Finally, you looked at a technique for using PHP start and

end tags in conjunction with conditional code blocks.



You should now have enough information to write scripts of your own. These scripts can make decisions and

perform repetitive tasks. In the next hour, we will be looking at a way of adding even more power to your

applications. You will learn how functions enable you to organize your code, preventing duplication and improving

reusability.

[ Team LiB ]



This document is created with the unregistered version of CHM2PDF Pilot



[ Team LiB ]



Q&A



Q1:

Must a control structure's test expression result in a

Boolean value?

A1:

Ultimately, yes, but in the context of a test expression,

zero, an undefined variable, or an empty string will be

converted to false. All other values will evaluate to

true.

Q2:

Must I always surround a code block in a control

statement with brackets?

A2:

If the code you want executed as part of a control

structure consists of only a single line, you can omit

the brackets.

[ Team LiB ]



Xem Thêm
Tải bản đầy đủ (.pdf) (561 trang)

×