Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 73 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
73
Dung lượng
4,34 MB
Nội dung
[ Team LiB ] Workshop The workshop is designed to help you anticipate possible questions, review what you've learned, and begin putting your knowledge into practice. Quiz 1: How would you use an if statement to print the string "Youth message" to the browser if an integer variable, $age, is between 18 and 35? If $age contains any other value, the string "Generic message" should be printed to the browser. A1: $age = 22; if ( $age >= 18 && $age <= 35 ) { print "Youth message<BR>\n"; } else { print "Generic message<BR>\n"; } 2: How would you extend your code in question 1 to print the string "Child message" if the $age variable is between 1 and 17? A2: $age = 12; if ( $age >= 18 && $age <= 35 ) { print "Youth message<BR>\n"; } elseif ( $age >= 1 && $age <= 17 ) { print "Child message<BR>\n"; } else { print "Generic message<BR>\n"; } 3: How would you create a while statement that increments through and prints every odd number between 1 and 49? A3: $num = 1; while ( $num <= 49 ) { print "$num<BR>\n"; $num += 2; } 4: How would you convert the while statement you created in question 3 into a for statement? A4: for ( $num = 1; $num <= 49; $num += 2 ) { print "$num<BR>\n"; } Activity Review the syntax for control structures. Think about how the techniques you've learned will help you in your scripting. Perhaps some of the script ideas you develop will be able to behave in different ways according to user input, or will loop to display an HTML table. Start to build the control structures you will be using. Use temporary variables to mimic user input or database queries for the time being. [ Team LiB ] [ Team LiB ] Hour 6. Working with Functions Functions are at the heart of a well-organized script, making code easy to read and reuse. No large project would be manageable without them. Throughout this hour, we will investigate functions and demonstrate some of the ways in which they can save you from repetitive work. In this hour, you will learn How to define and call functions How to pass values to functions and receive values in return How to call a function dynamically using a string stored in a variable How to access global variables from within a function How to give a function a "memory" How to pass data to functions by reference How to create anonymous functions How to verify that a function exists before calling it [ Team LiB ] [ Team LiB ] What Is a Function? You can think of a function as a machine. A machine takes the raw materials you feed it and works with them to achieve a purpose or to produce a product. A function accepts values from you, processes them, and then performs an action (printing to the browser, for example), returns a new value, or both. If you needed to bake a single cake, you would probably do it yourself. If you needed to bake thousands of cakes, you would probably build or acquire a cake-baking machine. Similarly, when deciding whether to create a function, the most important factor to consider is the extent to which it can save you from repetition. A function is a self-contained block of code that can be called by your scripts. When called, the function's code is executed. You can pass values to functions, which will then work with them. When finished, a function can pass a value back to the calling code. [ Team LiB ] [ Team LiB ] Calling Functions Functions come in two flavors—those built in to the language and those you define yourself. PHP has hundreds of built-in functions. The very first script in this book, which appears in Hour 3, "Installing and Configuring PHP," consists of a single function call: print "Hello Web!"; In this example, we call the print() function, passing it the string "Hello Web!". The function then goes about the business of writing the string. A function call consists of the function name (print in this case) followed by parentheses. If you want to pass information to the function, you place it between these parentheses. A piece of information passed to a function in this way is called an argument. Some functions require that more than one argument be passed to them. Arguments in such cases must be separated by commas: some_function( $an_argument, $another_argument); print() is typical in that it returns a value. Most functions give you some information back when they've completed their task—they usually at least tell whether their mission was successful. print() returns a Boolean. The abs() function, for example, requires a signed numeric value and returns the absolute value of that number. Let's try it out in Listing 6.1. print() is not a typical function in that it does not require parentheses in order to run successfully: print("Hello Web!"); and print "Hello Web!"; are equally valid. This is an exception. All other functions require parentheses, whether or not they accept arguments. Listing 6.1 Calling the Built-in abs() Function 1: <html> 2: <head> 3: <title>Listing 6.1</title> 4: </head> 5: <body> 6: <?php 7: $num = -321; 8: $newnum = abs( $num ); 9: print $newnum; 10: // prints "321" 11: ?> 12: </body> 13: </html> In this example, we assign the value -321 to a variable $num. We then pass that variable to the abs() function, which makes the necessary calculation and returns a new value. We assign this to the variable $newnum and print the result. Put these lines into a text file called abs.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following: 321 In fact, we could have dispensed with temporary variables altogether, passing our number straight to abs(), and directly printing the result: print( abs( -321 ) ); We used the temporary variables $num and $newnum, though, to make each step of the process as clear as possible. Sometimes you can make your code more readable by breaking it up into a greater number of simple expressions. You can call user-defined functions in exactly the same way that we have been calling built-in functions. [ Team LiB ] [ Team LiB ] Defining a Function You can define a function using the function statement: function some_function( $argument1, $argument2 ) { // function code here } The name of the function follows the function statement and precedes a set of parentheses. If your function requires arguments, you must place comma-separated variable names within the parentheses. These variables will be filled by the values passed to your function. Even if your function doesn't require arguments, you must nevertheless supply the parentheses. The naming rules for functions are similar to the naming rules for variables, which you learned in Hour 4, "The Building Blocks of PHP." Names cannot include spaces, and they must begin with a letter or an underscore. Listing 6.2 declares a function. Listing 6.2 Declaring a Function 1: <html> 2: <head> 3: <title>Listing 6.2</title> 4: </head> 5: <body> 6: <?php 7: function bighello() { 8: print "<h1>HELLO!</h1>"; 9: } 10: bighello(); 11: ?> 12: </body> 13: </html> The script in Listing 6.2 simply outputs the string "HELLO" wrapped in an HTML <h1> element. Put these lines into a text file called bighello.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 6.1. Figure 6.1. Output of Listing 6.2. We declare a function bighello() that requires no arguments. Because of this, we leave the parentheses empty. bighello() is a working function but is not terribly useful. Listing 6.3 creates a function that requires an argument and actually does something helpful with it. Listing 6.3 Declaring a Function That Requires Arguments 1: <html> 2: <head> 3: <title>Listing 6.3</title> 4: </head> 5: <body> 6: <?php 7: function printBR( $txt ) { 8: print ("$txt<br>\n"); 9: } 10: printBR("This is a line"); 11: printBR("This is a new line"); 12: printBR("This is yet another line"); 13: ?> 14: </body> 15: </html> Put these lines into a text file called printbr.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 6.2. Figure 6.2. A function that prints a string with an appended <br> tag. In line 7, the printBR() function expects a string, so we place the variable name $txt between the parentheses when we declare the function. Whatever is passed to printBR() will be stored in $txt. Within the body of the function, in line 8, we print the $txt variable, appending a <br> element and a newline character to it. When we want to write a line to the browser, such as in line 10, 11, or 12, we can call printBR() instead of the built-in print(), saving us the bother of typing the <br> element. [ Team LiB ] [ Team LiB ] Returning Values from User-Defined Functions In the previous example, we output an amended string to the browser within the printBR() function. Sometimes, however, you will want a function to provide you with a value that you can work with yourself. If your function has transformed a string that you have provided, you may wish to get the amended string back so that you can pass it to other functions. A function can return a value using the return statement in conjunction with a value. The return statement stops the execution of the function and sends the value back to the calling code. Listing 6.4 creates a function that returns the sum of two numbers. Listing 6.4 A Function That Returns a Value 1: <html> 2: <head> 3: <title>Listing 6.4</title> 4: </head> 5: <body> 6: <?php 7: function addNums( $firstnum, $secondnum ) { 8: $result = $firstnum + $secondnum; 9: return $result; 10: } 11: print addNums(3,5); 12: // will print "8" 13: ?> 14: </body> 15: </html> Put these lines into a text file called addnums.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following: 8 Notice in line 7 that addNums() should be called with two numeric arguments (line 11 shows those to be 3 and 5 in this case). These are stored in the variables $firstnum and $secondnum. Predictably, addNums() adds the numbers contained in these variables together and stores the result in a variable called $result. [...]... between 0 and 12 and the day is between 0 and 31 MySQL does not automatically verify that the 30 th day of the second month (February 30 th) is a valid date The MySQL date and time data types are DATE— A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12 -31 For example, December 30 th, 19 73 would be stored as 19 73- 12 -30 DATETIME— A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-... Listing 6.9 Put these lines into a text file called numberedheading .php, and place... functions, tagWrap() (line 8) and underline() (line 15) The tagWrap() function accepts three strings: a tag, the text to be formatted, and an optional function name It returns a formatted string underline() requires a single argument—the text to be formatted and returns the text wrapped in tags When we first call tagWrap() on line 19, we pass it the character b and the string make me bold Because... accepts four string variables and returns a string that contains an HTML table element, enclosing each of the variables in its own cell [ Team LiB ] [ Team LiB ] Hour 7 Learning Basic SQL Commands This hour takes a break from all that PHP you've been learning and provides a primer on SQL syntax, which you will use to create and manipulate your MySQL database tables This is a very hands-on hour, and it assumes... WHERE clause, and the GROUP BY clause in SELECT How to select from multiple tables, using JOIN How to use the UPDATE and REPLACE commands to modify existing records How to use the DELETE command to remove records [ Team LiB ] [ Team LiB ] Learning the MySQL Data Types Properly defining the fields in a table is important to the overall optimization of your database You should use only the type and size of... BIGINT— A large integer that can be signed or unsigned If signed, the allowable range is from –92 233 72 036 854775808 to 92 233 72 036 854775807 If unsigned, the allowable range is from 0 to 184467440 737 09551615 You can specify a width of up to 11 digits FLOAT(M,D)— A floating-point number that cannot be unsigned You can define the display length (M) and the number of decimals (D) This is not required and. .. as an unsigned TINYINT, you won't be able to successfully insert that 256th record if ID is a primary key (and thus required) Date and Time Types MySQL has several data types available for storing dates and times, and these data types are flexible in their input In other words, you can enter dates that are not really days, such as February 30 —February has only 28 or 29 days, never 30 Also, you can... changes made to an argument in these cases will change the value of the original variable You can pass an argument by reference by adding an ampersand to the argument name in the function definition, as shown in line 7 Listing 6.14 Using a Function Definition to Pass an Argument to a Function by Reference 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: Listing 6.14 ... to functions, they are stored as copies in parameter variables Any changes made to these variables in the body of the function are local to that function and are not reflected beyond it This is illustrated in Listing 6. 13 Listing 6. 13 Passing an Argument to a Function by Value 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: Listing 6. 13 . script in this book, which appears in Hour 3, "Installing and Configuring PHP,& quot; consists of a single function call: print "Hello Web!"; In this example, we call the print(). produces the following: 32 1 In fact, we could have dispensed with temporary variables altogether, passing our number straight to abs(), and directly printing the result: print( abs( -32 1 ) ); We used. Whatever is passed to printBR() will be stored in $txt. Within the body of the function, in line 8, we print the $txt variable, appending a <br> element and a newline character to it. When