Скачать презентацию CHAPTER 4 Powering Scripts with Functions Slide 4 Скачать презентацию CHAPTER 4 Powering Scripts with Functions Slide 4

d1747f289018d7c9a5d205868f3632a3.ppt

  • Количество слайдов: 48

CHAPTER 4 Powering Scripts with Functions Slide 4 -1 CHAPTER 4 Powering Scripts with Functions Slide 4 -1

Objectives n n To learn to use several PHP functions useful for Web application Objectives n n To learn to use several PHP functions useful for Web application development To learn to write and use your own functions Slide 4 -2

Using Some Basic PHP Functions n n We previously discussed functions such as strlen(), Using Some Basic PHP Functions n n We previously discussed functions such as strlen(), trim(), strtolower(), strtoupper(), and substr(). In this section we examine several other useful functions including n Some basic numeric PHP functions—E. g. , the absolute value[abs()], square root [sqrt()], round [round()], integer checker[is_numeric()], and random number generation [rand()] functions. n The print() function—We will cover in more detail n The date function—We will discuss using the date() function to determine date and time information. Slide 4 -3

Some Basic PHP Functions n n n Absolute value Square root, Round, Integer checker Some Basic PHP Functions n n n Absolute value Square root, Round, Integer checker and Random number generation Slide 4 -4

The abs() Function n n The absolute value function takes a single numerical argument The abs() Function n n The absolute value function takes a single numerical argument and returns its absolute value. For example, the following $x=abs(-5); $y=abs(42); print "x=$x y=$y"; n Will output n x=5 y=42 Slide 4 -5

The sqrt() Function n n The square root function takes a single numerical argument The sqrt() Function n n The square root function takes a single numerical argument and returns its square root. For example, the following n n $x=sqrt(25); $y=sqrt(24); print "x=$x y=$y"; Will output n x=5 y=4. 898979485566 Slide 4 -6

The round() Function n n The round function takes a single numerical argument and The round() Function n n The round function takes a single numerical argument and returns the number rounded up or down to the nearest integer. For example, the following n n $x=round(-5. 456); $y=round(3. 7342); print "x=$x y=$y"; Will output x=-5 y=4 Slide 4 -7

The round() Function n You can include 2 nd argument to define the number The round() Function n You can include 2 nd argument to define the number of digits after the decimal point to round to. For example, n $x=round(-5. 456, 2); n $y=round(3. 7342, 3); n print "x=$x y=$y"; would output n x=-5. 46 y=3. 734 Slide 4 -8

The is_numeric() Function n n is_numeric() is useful for determining whether a variable is The is_numeric() Function n n is_numeric() is useful for determining whether a variable is a valid number or a numeric string. n It returns true or false. Consider the following example. . . if (is_numeric($input)) { print "Got Valid Number=$input"; } else { print "Not Valid Number=$input"; } n n If $input was “ 6” then would : Got Valid Number=6 If $input was “Happy” then would output: Not Valid Number=Happy Slide 4 -9

The rand() Function n n Use rand() to generate a random number. n You The rand() Function n n Use rand() to generate a random number. n You can use random numbers to simulate a dice roll or a coin toss or to randomly select an advertisement banner to display. rand() typically uses 2 arguments to define the range of numbers it should return (min and max limits), n For example the following returns a number 1 15 n $num = rand(1, 15); Slide 4 -10

The rand() Function - Part II n Use the srand microtime to seed rand() The rand() Function - Part II n Use the srand microtime to seed rand() and ensure it returns a random number, for example, n n srand ((double) microtime() * 10000000); $dice = rand(1, 6); print "Your random dice toss is $dice"; The random number generated in this case can be a 1, 2, 3, 4, 5, or 6. Slide 4 -11

More information on the print() Function n n You don’t need to use parenthesis More information on the print() Function n n You don’t need to use parenthesis with print() Double quotes means output the value of any variable: n n n Single quotes means output the actual variable name n n n $x = 10; print ("Mom, please send $x dollars"); $x = 10; print ('Mom, please send $x dollars'); To output a single variable’s value or expression, omit the quotation marks. n n $x=5; print $x*3; Slide 4 -12

Generating HTMLTags with print() n Usingle or double quotation statements can be useful when Generating HTMLTags with print() n Usingle or double quotation statements can be useful when generating HTML tags n n print ''; This above is easier to understand actually runs slightly faster than using all double quotation marks and the backslash () character : n print ""; Slide 4 -13

A Full Example. . . n Consider the following application: n Uses an HTML A Full Example. . . n Consider the following application: n Uses an HTML form to ask the end-user to guess the results of a coin flip: n n Heads Tails Slide 4 -14

Receiving Code 1. <html> 2. <head><title> Coin Flip Results </title></head> <body> <? php Check Receiving Code 1. 2. Coin Flip Results You got it right!'; Check whether the 8. } elseif ( $flip == 0 && $pick == 1 ) { coin flip is heads but 9. print "The flip=$flip, which is heads! "; the guess is tails. 10. print ' You got it wrong!'; Check whether both 11. } elseif ( $flip == 1 && $pick == 1 ) { the coin flip and the 12. print "The flip=$flip, which is tails! "; guess are tails. 13. print ' You got it right!'; Check whether the coin flip is tails but the guess is heads. Slide 4 -15

Receiving Code continued. . . 14. } elseif ( $flip == 1 && $pick Receiving Code continued. . . 14. } elseif ( $flip == 1 && $pick == 0 ) { 15. print "The flip=$flip, which is tails! "; 16. print ' You got it wrong!'; 17. } else { 18. print " Illegal state error!"; 19. } 20. ? > Slide 4 -16

Receiving Code With REGISTER_GLOBALS Off 1. <html> 2. <head><title> Coin Flip Results </title></head> <body> Receiving Code With REGISTER_GLOBALS Off 1. 2. Coin Flip Results You got it right!'; coin flip is heads but the guess is tails. 9. } elseif ( $flip == 0 && $pick == 1 ) { 10. print "The flip=$flip, which is heads! "; Check whether both 11. print ' You got it wrong!'; the coin flip and the 12. } elseif ( $flip == 1 && $pick == 1 ) { guess are tails. 13. print "The flip=$flip, which is tails! "; Check whether the coin flip is tails but the guess is heads. Slide 4 -17

You got it" src="https://present5.com/presentation/d1747f289018d7c9a5d205868f3632a3/image-18.jpg" alt="Receiving Code With REGISTER_GLOBALS Off, cont. . 14. print ' You got it" /> Receiving Code With REGISTER_GLOBALS Off, cont. . 14. print ' You got it right!'; 15. } elseif ( $flip == 1 && $pick == 0 ) { 16. print "The flip=$flip, which is tails! "; 17. print ' You got it wrong!'; 18. } else { 19. print " Illegal state error!"; 20. } 21. ? > Slide 4 -18

The Output. . . The previous code can be executed at http: //webwizard. aw. The Output. . . The previous code can be executed at http: //webwizard. aw. com/~phppgm/C 3/headsortail. html Slide 4 -19

The date()Function n n The date() function is a useful function for determining the The date()Function n n The date() function is a useful function for determining the current date and time The format string defines the format of the date() function’s output: n n n $day = date('d'); print "day=$day"; Request date() to return the numerical day of the month. If executed on December 27, 2001, then it would output “day=27”. Slide 4 -20

Selected character formats for date() Slide 4 -21 Selected character formats for date() Slide 4 -21

More About date() n You can combine multiple character formats return more than one More About date() n You can combine multiple character formats return more than one format from the date() n For example, n n n $today = date( 'l, F d, Y'); print "Today=$today"; On December 27, 2001, would output n “Today=Thursday, December 27, 2001”. Slide 4 -22

A Full Example. . . n Consider the following Web application that uses date() A Full Example. . . n Consider the following Web application that uses date() to determine the current date and the number of days remaining in a store’s sale event. Slide 4 -23

" src="https://present5.com/presentation/d1747f289018d7c9a5d205868f3632a3/image-24.jpg" alt="Receiving Code 1. Our Shop 2. " /> Receiving Code 1. Our Shop 2. 3. "; 6. $month = date('m'); 7. $year = date('Y'); 8. $dayofyear = date('z'); 9. if ($month == 12 && $year == 2001) { 10. $daysleft = (365 - $dayofyear + 10); 11. print " There are $daysleft sales days left"; 12. } elseif ($month == 01 && $year == 2002) { 13. if ($dayofyear <= 10) { 14. $daysleft = (10 - $dayofyear); 15. print " There are $daysleft sales days left"; 16. } else { 19. print " Sorry, our sale is over. "; 20. } 21. } else { 22. print " Sorry, our sale is over. "; 23. } 24. print " Our Sale Ends January 10, 2002"; 25. ? > Slide 4 -24

The Output. . . The previous code can be executed at http: //webwizard. aw. The Output. . . The previous code can be executed at http: //webwizard. aw. com/~phppgm/C 3/date. php Slide 4 -25

The Perl Programming Language n Programmer-defined functions provide a way to group a set The Perl Programming Language n Programmer-defined functions provide a way to group a set of statements, set them aside, and turn them into mini-scripts within a larger script. n Scripts that are easier to understand change. n Reusable script sections. n Smaller program size Slide 4 -26

Writing Your Own Functions n Use the following general format Include parentheses at the Writing Your Own Functions n Use the following general format Include parentheses at the end of the function name function_name() { set of statements } Enclose in curly brackets. The function runs these statements when called Slide 4 -27

For example … n Consider the following: function Output. Table. Row() { print '<tr><td>One</td><td>Two</td></tr>'; For example … n Consider the following: function Output. Table. Row() { print 'OneTwo'; } n You can run the function by executing Output. Table. Row(); Slide 4 -28

As a full example … 1. <html> 2. <head><title> Simple Table Function </title> </head> As a full example … 1. 2. Simple Table Function 3. Here Is a Simple Table

Output. Table. Row() 4. '; 7. } 8. Output. Table. Row(); 9. Output. Table. Row(); 10. Output. Table. Row(); Three consecutive calls 11. ? > 12.
OneTwo
to the Output. Table. Row() function Slide 4 -29

Would have the following output … Slide 4 -30 Would have the following output … Slide 4 -30

TIP: Use Comments at the Start of a Function n n It is good TIP: Use Comments at the Start of a Function n n It is good practice to place comments at the start of a function For example, function Output. Table. Row() { // Simple function that outputs 2 table cells print 'OneTwo'; } Slide 4 -31

Passing Arguments to Functions n n Input variables to functions are called arguments to Passing Arguments to Functions n n Input variables to functions are called arguments to the function For example, the following sends 2 arguments n n Output. Table. Row("A First Cell", "A Second Cell"); Within function definition can access values function Output. Table. Row($col 1, $col 2) { print "$col 1$col 2"; } Slide 4 -32

Consider the following code … 1. <html> 2. <head><title> Simple Table Function </title> </head> Consider the following code … 1. 2. Simple Table Function 3. Revised Simple Table

4. "; Function definition. 7. } 8. for ( $i=1; $i<=4; $i++ ) { 9. $message 1="Row $i Col 1"; 10. $message 2="Row $i Col 2"; 11. Output. Table. Row( $message 1, $message 2 ); Four calls to 12. } Ouput. Table. Row() 13. ? > 14.
$col 1$col 2
Slide 4 -33

Would output the following … Slide 4 -34 Would output the following … Slide 4 -34

Returning Values n n Your functions can return data to the calling script. n Returning Values n n Your functions can return data to the calling script. n For example, your functions can return the results of a computation. You can use the PHP return statement to return a value to the calling script statement: return $result; This variable’s value will be returned to the calling script. Slide 4 -35

Example function 1. function Simple_calc( $num 1, $num 2 ) { 2. // PURPOSE: Example function 1. function Simple_calc( $num 1, $num 2 ) { 2. // PURPOSE: returns largest of 2 numbers 3. // ARGUMENTS: $num 1 -- 1 st number, $num 2 -- 2 nd number 4. if ($num 1 > $num 2) { 5. return($num 1); Return $num 1 when it 6. } else { is the larger value. 7. return($num 2); 8. } Return $num 2 when 9. } What is output if called as follows: $largest = Simple_calc(15, -22); is the larger value. it Slide 4 -36

A Full Example. . . n n Consider a script that calculates the percentage A Full Example. . . n n Consider a script that calculates the percentage change from starting to an ending value Uses the following front-end form: Starting Value: Ending Value: Slide 4 -37

The Source Code. . . 1. <html> 2. <head><title> Your Percentage Calculation </title></head><body> 3. The Source Code. . . 1. 2. Your Percentage Calculation 3. Percentage Calculator 4. Calculate the percentage change from the starting value to the ending value. The call to Calc_perc() returns the percentage change into $per. Slide 4 -38

The Source Code with REGISTER_GLOABLS Off 1. <html> 2. <head><title> Your Percentage Calculation </title></head><body> The Source Code with REGISTER_GLOABLS Off 1. 2. Your Percentage Calculation 3. Percentage Calculator 4. Calculate the percentage change from the starting value to the ending value. The call to Calc_perc() returns the percentage change into $per. Slide 4 -39

Would Output The Following. . . Slide 4 -40 Would Output The Following. . . Slide 4 -40

A Full Script Example (with RESGISTER_GLOBALS off). . . 1. <html> 2. <head><title>While Loop</title></head> A Full Script Example (with RESGISTER_GLOBALS off). . . 1. 2. While Loop 3. 4. Table of Square and Cube Values 5.

6. 7. "); 14. $i = $i + 1; 15. } 16. ? >
Numb Sqr Cubed $i$sqr$cubed
Slide 4 -41

The Output … The previous code can be executed at http: //webwizard. aw. com/~phppgm/C The Output … The previous code can be executed at http: //webwizard. aw. com/~phppgm/C 3/whileloop. php Slide 4 -42

Using External Script Files n n Sometime you will want to use scripts from Using External Script Files n n Sometime you will want to use scripts from external files. PHP supports 2 related functions: The require() function The include() function produces a warning if it can’t insert the specified file. n require ("header. php"); include ("trailer. php"); produces a fatal error if it can’t insert the specified file. Both search for the file named within the double quotation marks and insert its PHP, HTML, or Java. Script code into the current file. Slide 4 -43

2. Welcome to Harry’s Hardware Heaven!" src="https://present5.com/presentation/d1747f289018d7c9a5d205868f3632a3/image-44.jpg" alt="Consider the following example 1. 2. Welcome to Harry’s Hardware Heaven!" /> Consider the following example 1. 2. Welcome to Harry’s Hardware Heaven! 3. We sell it all for you! 4. The script will output these lines when the file is included. The value of $time will be set when the file is included. This function will be available for use when the file is included. Slide 4 -44

header. php n If the previous script is placed into a file called header. header. php n If the previous script is placed into a file called header. php … 1. Hardware Heaven 2. 11. Slide 4 -45

Would output the following. . . Slide 4 -46 Would output the following. . . Slide 4 -46

More Typical Use of External Code Files n n More typically might use one More Typical Use of External Code Files n n More typically might use one or more files with only functions and other files that contain HTML For example, might use the following as footer. php.


Hardware Harry's is located in beautiful downtown Hardwareville. We are open every day from 9 A. M. to midnight, 365 days a year. Call 476 -123 -4325. Just ask for Harry. n Can include using: Slide 4 -47

Summary n n PHP provides several functions useful including abs(), round(), is_numeric(), rand(), date() Summary n n PHP provides several functions useful including abs(), round(), is_numeric(), rand(), date() Programmer-defined functions allow you to group a set of statements, set them aside, and turn those grouped statements into mini-scripts. Slide 4 -48