SAMS Teach Yourself PHP4 in 24 Hours phần 3 pdf

45 261 0
  • Loading ...
    Loading ...
    Loading ...

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Tài liệu liên quan

Thông tin tài liệu

Ngày đăng: 06/08/2014, 09:20

91 13: </body> 14: </html> The script in Listing 6.2 will simply output the string "HELLO" wrapped in an HTML <H1> element. We declare a function bighello() that requires no arguments. Because of this, we leave the parentheses empty. bighello() is a working function but 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: { 9: print ("$txt<br>\n"); 10: } 11: printBR("This is a line"); 12: printBR("This is a new line"); 13: printBR("This is yet another line"); 14: ?> 15: </body> 16: </html> Figure 6.1: A function that prints a string with an appended <BR> tag. 92 You can see the output from the script in Listing 6.3 in Figure 6.1. 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() is stored in $txt. Within the body of the function, we print the $txt variable, appending a <br> element and a newline character to it. Now when we want to write a line to the browser, we can call printBR() instead of the built-in print(), saving us the bother of typing the <br> element. Returning Values from User-Defined Functions A function can return a value using the return statement in conjunction with a value or object. return 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: { 9: $result = $firstnum + $secondnum ) 10: return $result;11: } 12: print addNums(3,5); 13: // will print "8" 14: ?> 15: </body> 16: </html> The script in Listing 6.4 will print the number '8'. addNums() should be called with two numeric arguments (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. Once again, we can dispense with a stage in this code, doing away with the temporary $result variable altogether: function addNums( $firstnum, $secondnum ) { 93 return ( $firstnum + $secondnum ); } The return statement can return a value, an object, or even nothing at all. How a value passed by return is arrived at can vary. The value could be hard-coded: return 4; It could be the result of an expression: return ( $a/$b ); It could be the value returned by yet another function call: return ( another_function( $an_argument ) ); Dynamic Function Calls It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Listing 6.5 creates a simple example of this. Listing 6.5: Calling a Function Dynamically 1: <html> 2: <head> 3: <title>Listing 6.5</title> 4: </head> 5: <body> 6: <?php 7: function sayHello() 8: { 9: print "hello<br>"; 10: } 11: $function_holder = "sayHello"; 12: $function_holder(); 13: ?> 14: </body> 15: </html> A string identical to the name of the sayHello() function is assigned to the $function_holder variable. Once this is done, we can use this variable in conjunction with parentheses to call the sayHello() function. Why would we want to do this? In the example, we simply made more work for ourselves by assigning the string "sayHello" to $function_holder. Dynamic function calls are useful when you want to alter program flow according to changing circumstances. We might want our script to behave differently according to a 94 parameter set in a URL's query string, for example. We could extract the value of this parameter and use it to call one of a number of functions. PHP's built-in functions also make use of this feature. The array_walk() function, for example uses a string to call a function for every element in an array. You can see an example of array walk() in action in Hour 16. Variable Scope A variable declared within a function remains local to that function. In other words, it will not be available outside the function or within other functions. In larger projects, this can save you from accidentally overwriting the contents of a variable when you declare two variables of the same name in separate functions. Listing 6.6 creates a variable within a function and then attempts to print it outside the function. Listing 6.6: Variable Scope: A Variable Declared Within a Function Is Unavailable Outside the Function 1: <html> 2: <head> 3: <title>Listing 6.6</title> 4: </head> 5: <body> 6: <?php 7: function test() 8: { 9: $testvariable = "this is a test variable"; 10: } 11: print "test variable: $testvariable<br>"; 12: ?> 13: </body> 14: </html> 95 Figure 6.2: Attempting to reference a variable defined within a function. You can see the output of the script in Listing 6.6 in Figure 6.2. The value of the variable $testvariable is not printed. This is because no such variable exists outside the test() function. Note that attempting to access a nonexistent variable does not cause an error. Similarly, a variable declared outside a function will not automatically be available within it. Accessing Variables with the global Statement From within a function, it is not possible by default to access a variable that has been defined elsewhere. If you attempt to use a variable of the same name, you will set or access a local variable only. Let's put this to the test in Listing 6.7. Listing 6.7: Variables Defined Outside Functions Are Inaccessible from Within a Function by Default 1: <html> 2: <head> 3: <title>Listing 6.7</title> 4: </head> 5: <body> 6: <?php 7: $life = 42; 8: function meaningOfLife() 96 9: { 10: print "The meaning of life is $life<br>"; 11: } 12: meaningOfLife(); 13: ?> 14: </body> 15: </html> You can see the output from the script in Listing 6.7 in Figure 6.3. As you might expect, the meaningOfLife() function has no access to the $life variable; $life is empty when the function attempts to print it. On the whole, this is a good thing. We're saved from potential clashes between identically named variables, and a function can always demand an argument if it needs information about the outside world. Occasionally, however, you may want to access an important global variable from within a function without passing it in as an argument. This is where the global statement comes into its own. Listing 6.8 uses global to restore order to the universe. Figure 6.3: Attempting to print a global variable from within a function. Listing 6.8: Accessing Global Variables with the global Statement 1: <html> 2: <head> 3: <title>Listing 6.8</title> 4: </head> 5: <body> 97 6: <?php 7: $life=42; 8: function meaningOfLife() 9: { 10: global $life; 11: print "The meaning of life is $life<br>"; 12: } 13: meaningOfLife(); 14: ?> 15: </body> 16: </html> You can see the output from the script in Listing 6.8 in Figure 6.4. By placing global in front of the $life variable when we declare it in the meaning_of_life() function, we make it refer to the global $life variable declared outside the function. You will need to use the global statement for every function that wishes to access a particular global variable. Be careful, though. If we manipulate the contents of the variable within the function, $life will be changed for the script as a whole. Usually, an argument is a copy of whatever value is passed by the calling code; changing it in a function has no effect beyond the function block. Changing a global variable within a function on the other hand changes the original and not a copy. Use the global statement sparingly. Figure 6.4: Successfully accessing a global variable from within a function using 98 the global keyword. Saving State Between Function Calls with the static Statement Variables within functions have a short but happy life on the whole. They come into being when the andAnotherThing() function is called and die when execution is finished. Once again, this is as it should be. It is usually best to build a script as a series of self-contained blocks, each with as little knowledge of others as possible. Occasionally, however, you may want to give a function a rudimentary memory. Let's assume that we want a function to keep track of the number of times it has been called. Why? In our examples, the function is designed to create numbered headings in a script that dynamically builds online documentation. We could, of course use our newfound knowledge of the global statement to do this. We have a crack at this in Listing 6.9. Listing 6.9: Using the global Statement to Remember the Value of a Variable Between Function Calls 1: <html> 2: <head> 3: <title>Listing 6.9</title> 4: </head> 5: <body> 6: <?php 7: $num_of_calls = 0; 8: function andAnotherThing( $txt ) 9: { 10: global $num_of_calls; 11: $num_of_calls++; 12: print "<h1>$num_of_calls. $txt</h1>"; 13: } 14: andAnotherThing("Widgets"); 15: print("We build a fine range of widgets<p>"); 16: andAnotherThing("Doodads"); 17: print("Finest in the world<p>"); 18: ?> 19: </body> 20: </html> 99 Figure 6.5: Using the global statement to keep track of the number of times a function has been called. This does the job. We declare a variable, $num_of_calls, outside the function andAnotherThing(). We make this variable available to the function with the global statement. You can see the output of Listing 6.9 in Figure 6.5. Every time andAnotherThing() is called, $num_of_calls is incremented. We can then print out a heading complete with a heading number. This is not the most elegant solution, however. Functions that use the global statement cannot be read as standalone blocks of code. In reading or reusing them, we need to look out for the global variables that they manipulate. This is where the static statement can be useful. If you declare a variable within a function in conjunction with the static statement, the variable remains local to the function. On the other hand, the function "remembers" the value of the variable from execution to execution. Listing 6.10 adapts the code from Listing 6.9 to use the static statement. Listing 6.10: Using the static Statement to Remember the Value of a Variable Between Function Calls 1: <html> 2: <head> 3: <title>Listing 6.10</title> 4: </head> 5: <body> 6: <?php 7: function andAnotherThing( $txt ) 8: { 9: static $num_of_calls = 0; 10: $num_of_calls++; 100 11: print "<h1>$num_of_calls. $txt</h1>"; 12: } 13: andAnotherThing("Widgets"); 14: print("We build a fine range of widgets<p>"); 15: andAnotherThing("Doodads"); 16: print("Finest in the world<p>"); 17: ?> 18: </body> 19: </html> andAnotherThing() has become entirely self-contained. When we declare the $num_of_calls variable, we assign an initial value to it. This initial assignment is ignored when the function is called a second time. Instead, the previous value of $num_of_calls is remembered. We can now paste the andAnotherThing() function into other scripts without worrying about global variables. Although the output of Listing 6.10 is exactly the same as that for Listing 6.9, we have made the code more elegant. More About Arguments You've already seen how to pass arguments to functions, but there's more to cover yet. In this section, you'll look at a technique for giving your arguments default values and explore a method of passing references to variables rather than copies of their values to your functions. Setting Default Values for Arguments PHP gives you a nifty feature to help build flexible functions. Until now, we've said that some functions "demand" one or more arguments. By making some arguments optional, you can render your functions a little less autocratic. Listing 6.11 creates a useful little function that wraps a string in an HTML font element. We want to give the user of the function the chance to change the font element's size attribute, so we demand a $size argument in addition to the string. Listing 6.11: A Function Requiring Two Arguments 1: <html> 2: <head> [...]... occupation=>"arch villain", 18: age=> 63, 19: specialty=>"nanotechnology" ) 20: 21: ); 118 22: foreach ( $characters as $val ) 23: { 24: foreach ( $val as $key=>$final_val ) 25: { 26: print "$key: $final_val"; 27: } 28: print ""; 29: } 30 : ?> 31 : 32 : You can see the output from Listing 7 .3 in Figure 7 .3 We create two foreach loops The outer loop accesses each element in the numerically indexed... Numerically indexed arrays are useful for storing values in the order in which they were added or according to a sort pattern Sometimes, though, you need to access elements in an array by name An associative array is indexed with strings between 111 the square brackets rather than numbers Imagine an address book Which would be easier, indexing the "name" field as 4 or as "name"? NEW Arrays indexed by strings... placed in the variable $val, which we then print to the browser If you are moving to PHP4 from Perl, be aware of a significant difference in the behavior of foreach Changing the value of the temporary variable in a Perl foreach loop changes the corresponding element in the array Changing the temporary variable in the preceding example would have no effect on the $users array You will look at a way of using... defaults Passing References to Variables to Functions When you pass arguments 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 03 1: 2: 3: Listing 6. 13... has only two elements, but the index of the final element is 200 PHP4 will not initialize the intervening elements This could lead to confusion when attempting to access elements in the array In addition to creating arrays, you can use the array identifier to add new values onto the end of an existing array In the following code, we define an array with the array() function and use the array identifier... print "$key = $val"; 16: } 17: 18: ?> 19: 20: You can see the output from Listing 7.2 in Figure 7.2 Outputting a Multidimensional Array You can now combine these techniques to output the multidimensional array created in Listing 7.1 Listing 7 .3 defines a similar array and uses foreach to loop through each of its elements 117 Figure 7.2: Looping through an associative array Listing... users Array Index Value Number Which Element? 0 Bert First 1 Sharon Second 2 Betty Third 3 Harry Fourth Indexing arrays by string can be useful in cases where you need to store both names and values PHP4 provides tools to access and manipulate arrays indexed by both name and number Some of these are covered in this hour, and others will be covered in Hour 16, "Working with Data." Creating Arrays By... and letters within a string, PHP will attempt to insert the value of a variable by that name In the example above we wished to print the string '$first' rather than the value of the $first variable To print the special character '$', therefore, we must precede it with a backslash PHP will now print the character instead of interpreting it This process is often referred to as "escaping" a character... from them using a foreach loop You should be able to combine arrays to create multidimensional arrays and loop through the information they contain You learned how to manipulate arrays by adding or removing multiple elements Finally, you learned some of the techniques that PHP4 makes available to sort arrays Q&A Q If the foreach statement was introduced with PHP4, how did programmers using PHP3 iterate... name=>"mary", 17: occupation=>"arch villain", 18: age=> 63, 19: specialty=>"nanotechnology" ) 1 13 20: ); 21: 22: print $characters[0][occupation]; 23: // prints "superhero" 24: ?> 25: 26: Notice that we have nested array function calls within an array function call At the first level, we define an array For each of its elements, we define an associative array Accessing $user[2], therefore, gives . it. This is illustrated in Listing 6. 13. Listing 6. 13: Passing an Argument to a Function by Value 1 03 1: <html> 2: <head> 3: <title>Listing 6. 13& lt;/title> 4: </head>. call printBR() instead of the built -in print(), saving us the bother of typing the <br> element. Returning Values from User-Defined Functions A function can return a value using the. the test in Listing 6.7. Listing 6.7: Variables Defined Outside Functions Are Inaccessible from Within a Function by Default 1: <html> 2: <head> 3: <title>Listing 6.7</title>
- Xem thêm -

Xem thêm: SAMS Teach Yourself PHP4 in 24 Hours phần 3 pdf, SAMS Teach Yourself PHP4 in 24 Hours phần 3 pdf, SAMS Teach Yourself PHP4 in 24 Hours phần 3 pdf

Từ khóa liên quan