1. Trang chủ
  2. » Công Nghệ Thông Tin

A Programmer’s Introduction to PHP 4.0 phần 3 ppt

47 329 0

Đang tải... (xem toàn văn)

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 47
Dung lượng 534,26 KB

Nội dung

Gilmore_03 12/4/00 1:04 PM Page 78 Chapter July 31, 2000|2:30pm|Progressive Gourmet|Forget the Chardonnay; iced tea is the sophisticated gourmet's beverage of choice August 1, 2000|7 p.m.|Coder's Critique|Famed Food Critic Brian rates NYC's hottest new Internet cafés August 3, 2000|6 p.m.|Australian Algorithms|Matt studies the alligator's diet Our PHP script shown in Listing 3-1 will produce the output seen in Figure 3-1 Figure 3-1 The sample events calendar Before delving into the code, take a moment to read through the algorithm, which will outline the series of commands executed by the code: Split each line into four elements: date, time, event title, and event summary Format and display the event information 78 Open the file containing the event information Close the file Gilmore_03 12/4/00 1:04 PM Page 79 Expressions, Operators, and Control Structures Listing 3-1: Script used to display contents of events.txt to browser This short example serves as further proof that PHP enables even novice programmers to develop practical applications while investing a minimum of time and learning Don’t worry if you don’t understand some of the concepts introduced; they are actually quite simple and will be covered in detail in later 79 Gilmore_03 12/4/00 1:04 PM Page 80 Chapter chapters However, if you just can’t wait to learn more about these subjects, jump ahead to Chapter 7, “File I/O and the File System,” and Chapter 8, “Strings and Regular Expressions,” as much of the unfamiliar syntax is described in those chapters What’s Next? This chapter introduced many of the features of the PHP language that you will probably implement in one form or another in almost every script you write: expressions and control structures Many topics using these features were explained, namely: • Operators • Operands • Operator precedence • Operator associativity • Control structures (if, while, while, for, foreach, switch, break, continue) The first three chapters served to introduce you to the core components of the PHP language The remaining five chapters of this first part of the book will build on these core components, providing you with further information regarding arrays, object-oriented features, file handling, and PHP’s string manipulations This all sets the stage for the second half of the book, serving to highlight PHP’s application-building features So hold on tight and read on! 80 Gilmore_04 12/4/00 1:04 PM Page 81 C H A P TER Functions This chapter introduces the general concepts of functional programming, one of the most influential advances in application development Functions enable you to develop reusable and easily modifiable components, which are particularly useful when you need to develop Web applications similar in concept and utility Functional programming results in shorter, easier to read programs In particular, this chapter is concerned with the creation, implementation, and manipulation of PHP functions Although the general focus is on defining and executing user-defined functions, it is also important to know that PHP offers hundreds of predefined functions Predefined functions are used exactly as userdefined functions are and save considerable time for developing new applications For the most up-to-date listing of these functions, check out http://www.php.net What Is a Function? A function is a section of code with a specific purpose that is assigned a unique name The function name can be called at various points in a program, allowing the section of code represented by this name to be repeatedly executed as needed This is convenient because the same section of code is written only once, but can be easily modified as necessary Function Definition and Invocation Creating a PHP function is a rather straightforward process You can create a function at any point in a PHP program However, for organizational purposes you may find it convenient to place all functions intended for use in a script at the very top of the script file An alternative method for function organization that can greatly reduce redundancy and promote code reuse is the placement of the functions in a separate file (also known as a library) This is convenient because you can use the functions repeatedly in various applications without having to make redundant copies and thus risk errors due to rewriting I explain this process in detail toward the conclusion of this chapter, in “Building Function Libraries.” 81 Gilmore_04 12/4/00 1:04 PM Page 82 Chapter A function definition generally consists of three distinct parts: • The name of the function • Parentheses enclosing an optional set of comma-delimited input parameters • The body of the function, enclosed in curly brackets The general form of a PHP function is as follows: function function_name (optional $arg1, $arg2, , $argn) { code section } The function name must follow the lexical structure conditions as specified in Chapter 2, “Variables and Data Types.” The function name is then followed by a mandatory set of parentheses, enclosing an optional set of input parameters ($arg1, $arg2, , $argn) Due to PHP’s relatively relaxed perspective on variable definitions, there is no need to specify the data type of the input parameters While this has its advantages, realize that the PHP engine does not verify that the data passed into the function is intended to be handled by the function This could result in unexpected results if the input parameter is used in an unintended fashion (To ensure that the input parameter is being used as intended, you can test it using the predefined gettype() function.) A set of curly brackets ({}) follows the closing parentheses, enclosing the section of code to be associated with the function name Let’s consider a simple example of practical usage of a function Suppose you wanted to create a function that outputs a general copyright notice to a Web page: function display_copyright() { print "Copyright © 2000 PHP-Powered Recipes All Rights Reserved."; } Assuming that your Web site contains many pages, you could simply call this function at the bottom of each page, eliminating the need to continually rewrite the same information Conveniently, the arrival of the year 2001 will bring about one simple modification of the text contained in the function that will result in an updated copyright statement If functional programming weren’t possible, you would have to modify every page in which the copyright statement was included! Consider a variation of the display_copyright() function in which we pass a parameter Suppose that you were in charge of the administration of several Web sites, each with a different name Further imagine that each site had its own ad- 82 Gilmore_04 12/4/00 1:04 PM Page 83 Functions ministration script, consisting of various variables relative to the specific site, one of the variables being $site_name With this in mind, the function display_copyright() could be rewritten as follows: function display_copyright($site_name) { print "Copyright © 2000 $site_name All Rights Reserved."; } The variable $site_name, assigned a value from somewhere outside of the function, is passed into display_copyright() as an input parameter It can then be used and modified anywhere in the function However, modifications to the variable will not be recognized anywhere outside of the function, although it is possible to force this recognition through the use of special keywords These keywords, along with a general overview of variable scoping as it relates to functions, were introduced in Chapter 2, “Variables and Data Types.” Nested Functions It is also possible to nest functions within functions, much as you can insert one control structure (if, while, for, and so on) within another This is useful for programs large and small, as it adds another level of modularization to the application, resulting in increasingly manageable code Revisiting the copyright example described earlier, you can eliminate the need to modify the date altogether by nesting PHP’s predefined date() function in the display_copyright() function: function display_copyright($site_name) { print "Copyright ©" date("Y") " $site_name All Rights Reserved."; } The Y input parameter of the date() function specifies that the return value should be the current year, formatted using four digits Assuming that the system date configuration is correct, PHP will output the correct year on each invocation of the script PHP’s date() function is extremely flexible, offering 25 different date- and time-formatting flags You can also nest function declarations inside one another However, nesting a function declaration does not imply that it is protected in the sense of it being limited to use only in the function in which it is declared Furthermore, a nested function does not inherit the input parameters of its parent; they must be passed to the nested function just as they are passed to any other function Regardless, you may find it useful to nest function declarations for reasons of code management and clarity Listing 4-1 gives an example of nesting function declarations 83 Gilmore_04 12/4/00 1:04 PM Page 84 Chapter Listing 4-1: Making efficient use of nested functions function display_footer($site_name) { function display_copyright($site_name) { print "Copyright © " date("Y") " $site_name All Rights Reserved."; } print " home | recipes | events tutorials | about | contact us"; display_copyright($site_name); print ""; } $site_name = "PHP Recipes"; display_footer($site_name); Executing this script produces the following output: home | recipes | events tutorials | about | contact us Copyright © 2000 PHP Recipes All Rights Reserved NOTE It is important to note that we could also call display_copyright() from outside the display_footer() function, just as display_footer() was called in the preceding example PHP does not support the concept of protected functions Although nested functions are not protected from being called from any other location of the script, they cannot be called until after their parent function has been called An attempt to call a nested function before calling its parent function results in an error message 84 Gilmore_04 12/4/00 1:04 PM Page 85 Functions Returning Values from a Function It is often useful to return a value from a function This is accomplished by assigning the function call to a variable Any type may be returned from a function, including lists and arrays Consider Listing 4-2, in which the sales tax for a given price is calculated and the total cost subsequently returned Before checking out the code, take a minute to review the pseudocode summary: • Assume that a few values have been set, in this case some product price, $price, and sales tax, $tax • Declare function calculate_cost() It accepts two parameters, the sales tax and the product price • Calculate the total cost and use return to send the calculated cost back to the caller • Call calculate_cost(), setting $total_cost to whatever value is returned from the function • Output a relevant message Listing 4-2: Building a function that calculates sales tax $price = 24.99; $tax = 06; function calculate_cost($tax, $price) { $sales_tax = $tax; return $price + ($price * $sales_tax); } // Notice how calculate_cost() returns a value $total_cost = calculate_cost ($tax, $price); // round the cost to two decimal places $total_cost = round($total_cost, 2); print "Total cost: ".$total_cost; // $total_cost = 26.49 NOTE A function that does not return a value is also known as a procedure 85 Gilmore_04 12/4/00 1:04 PM Page 86 Chapter Another way in which to use returned values is to incorporate the function call directly into a conditional/iterative statement Listing 4-3 checks a user’s total bill against a credit limit The pseudocode is found here: • Declare function check_limit(), which takes as input two parameters The first parameter, $total_cost, is the total bill accumulated by the user thus far The second, $credit_limit, is the maximum cash amount the user is allowed to charge • If the total accumulated bill is greater than the credit limit, return a false (0) value • If the if statement evaluates to false, then the function has not yet terminated Therefore, the total cost has not exceeded the credit limit, and true should be returned • Use the function check_limit() in an if conditional statement Check_limit() will return either a true or a false value This returned value will determine the action that the if statement takes If check_limit() evaluates to true, tell the user to keep shopping Otherwise, inform that user that the credit limit has been exceeded Listing 4-3: Comparing a user’s current bill against a credit limit $cost = 1456.22; $limit = 1000.00; function check_limit($total_cost, $credit_limit) { if ($total_cost > $credit_limit) : return 0; endif; return 1; } if (check_limit($cost, $limit)) : // let the user keep shopping print "Keep shopping!"; else : print "Please lower your total bill to less than $".$limit."!"; endif; 86 Gilmore_04 12/4/00 1:04 PM Page 87 Functions Execution of Listing 4-3 results in the error message being displayed, since $cost has exceeded $limit It is also possible to simultaneously return multiple values from a function by using a list Continuing with the culinary theme, consider a function that returns the three recommended years of a particular wine This function is illustrated in Listing 4-4 Read through the pseudocode first: • Declare function best_years(), which takes as input one parameter The parameter $label is the type of wine in which the user would like to view the three recommended years • Declare two arrays, $merlot, and $zinfandel Each array holds the three recommended years for that wine type • Implement the return statement to make wise use of the variable functionality The statement $$label will first interpret the variable $label and then interpret whatever the value of $label is as another variable In this case, the merlot array will be returned as a list, each year taking its respective position in the calling list • Print out a relevant message, informing the user of these recommended years Listing 4-4: Returning multiple values from a function // wine for which best years will be displayed $label = "merlot"; // This function merely makes use of various arrays and a variable variable to return multiple values function best_years($label) { $merlot = array(1987, 1983, 1977); $zinfandel = array(1992, 1990, 1989); return $$label; } // a list() Is used to display the wine's best years list ($yr_one, $yr_two, $yr_three) = best_years($label); print "$label had three particularly remarkable years: $yr_one, $yr_two, and $yr_three."; 87 Gilmore_05 12/5/00 10:23 AM Page 109 Arrays array_flip() The array_flip() function will exchange (“flip”) all key and element values for the array Its syntax is: array array_flip(array array) Here’s how you could use array_flip() to flip all key and element values: $languages = array("Spain" => "Spanish", "France" => "French", "Italy" => "Italian"); $languages = array_flip($languages); // $languages = array("Spanish" => "Spain", // "French" => "France", // "Italian" => "Italy"); Keep in mind that array_flip() only flips the key/value mapping and does not reverse the positioning To reverse the positioning of the elements, use array_reverse() Array Size Knowledge of the current size of an array has many applications when coding efficient scripts Other than using the size for simple referential purposes, perhaps the most common use of the array size is for looping through arrays: $us_wine_producers = array ("Washington", "New York", "Oregon", "California"); for ($i = 0; $i < sizeof ($us_wine_producers); $i++) : print "$us_wine_producers[$i]"; endfor; Because the $us_wine_producers array is indexed by integer value, you can use a for loop to iteratively increment a counting variable ($i) and display each element in the array sizeof() The function sizeof() is used to return the number of elements contained in an array Its syntax is: 109 Gilmore_05 12/5/00 10:23 AM Page 110 Chapter int sizeof (array array) You will probably use the sizeof()function often in your Web applications A brief example of its usage follows The previous example is another common usage of the sizeof() function $pasta = array("bowties", "angelhair", "rigatoni"); $pasta_size = sizeof($pasta); // $pasta_size = An alternative, extended form of sizeof() is count(), next count() The count() function performs the same operations as sizeof(), returning the number of values contained in an array Its syntax is: int count (mixed variable) The only difference between sizeof() and count() is that count() provides a bit more information in some situations: • If the variable exists and is an array, count() will return the number of elements contained in the array • If the variable exists but is not an array, the value ‘1’ will be returned • If the variable does not exist, the value ‘0’ will be returned array_count_values() The array_count_values() function is a variation of sizeof() and count(), instead counting the frequency of the values appearing in the array Its syntax is: array array_count_values (array array); The returned array will use the values as keys and their corresponding frequencies as the values, as illustrated here: $states = array("OH", "OK", "CA", "PA", "OH", "OH", "PA", "AK"); $state_freq = array_count_values($states); 110 Gilmore_05 12/5/00 10:23 AM Page 111 Arrays The array $state_freq will now contain the following key/value associations: $state_freq = array("OH" => 3, "OK" => 1, "CA" => 1, "PA" => 2, "AK" => 1); Sorting Arrays The importance of sorting routines can hardly be understated in the realm of programming and can be seen in action in such online applications as ecommerce sites (sorting categories by alphabetical order), shopping bots (sorting prices), and software search engines (sorting software by number of downloads) PHP offers the nine predefined sorting functions listed in Table 5-1, each sorting an array in a unique fashion Table 5-1 Sort Function Summary FUNCTION SORT BY REVERSE SORT? MAINTAIN KEY/VALUE CORRELATION? sort rsort asort arsort ksort krsort Value Value Value Value Key Key No Yes No Yes No Yes No No Yes Yes Yes Yes usort Value ? No uasort uksort Value Key ? ? Yes Yes ? applies to the user-defined sorting functions, where the order in which the array is sorted depends on the results brought about by the user-defined function You are not limited to using predefined criteria for sorting your array information, as three of these functions (usort(), uasort(), and uksort()) allow you to introduce array-specific criteria to sort the information any way you please sort() The sort() function is the most basic sorting function, sorting array elements from lowest to highest value Its syntax is: void sort (array array) 111 Gilmore_05 12/5/00 10:23 AM Page 112 Chapter Nonnumerical elements will be sorted in alphabetical order, according to their ASCII values This basic example illustrates use of the sort function: // create an array of cities $cities = array ("Aprilia", "Nettuno", "Roma", "Venezia", "Anzio"); // sort the cities from lowest to highest value sort($cities); // cycle through the array, printing each key and value for (reset ($cities); $key = key ($cities); next ($cities)) : print "cities[$key] = $cities[$key] "; endfor; Executing the preceding code yields: cities[0] = Anzio cities[1] = Aprilia cities[2] = Nettuno cities[3] = Roma cities[4] = Venezia As you can see, the $cities array has been sorted in alphabetical order A variation on this algorithm is asort(), introduced later in this chapter rsort() The rsort() function operates exactly like the sort() function, except that it sorts the elements in reverse order Its syntax is: void rsort (array array) Reconsider the $cities array, first introduced in the preceding example: $cities = array ("Aprilia", "Nettuno", "Roma", "Venezia", "Anzio") rsort($cities); 112 Gilmore_05 12/5/00 10:23 AM Page 113 Arrays Using rsort() to sort the $cities array results in the following reordering: cities[0] = Venezia cities[1] = Roma cities[2] = Nettuno cities[3] = Aprilia cities[4] = Anzio Once again, the $cities array is sorted, but this time in reverse alphabetical order A variation of this function is arsort(), described later in this chapter asort() The asort() function works much like the previously explained sort() function, except that the array indexes maintain their original association with the elements regardless of the new position the element assumes The function’s syntax is: void asort (array array) Revisiting the $cities array: $cities = array ("Aprilia", "Nettuno", "Roma", "Venezia", "Anzio"); asort($cities); Use asort() to sort the $cities array, which yields this new array ordering: cities[4] = Anzio cities[0] = Aprilia cities[1] = Nettuno cities[2] = Roma cities[3] = Venezia Note the index values and compare them to those in the example accompanying the introduction to sort() This is the differentiating factor between the two functions arsort() The arsort() function is a variation of asort(), maintaining the original index association but instead sorting the elements in reverse order Its syntax is: void arsort (array array) 113 Gilmore_05 12/5/00 10:23 AM Page 114 Chapter Using arsort() to sort the $cities array: $cities = array ("Aprilia", "Nettuno", "Roma", "Venezia", "Anzio"); arsort($cities); results in the array being sorted in the following order: cities[3] = Venezia cities[2] = Roma cities[1] = Nettuno cities[0] = Aprilia cities[4] = Anzio Note the index values and compare them to those in the example accompanying the introduction to rsort() This is the differentiating factor between the two functions ksort() The ksort() function sorts an array according to its key values, maintaining the original index association Its syntax is: void ksort (array array) Consider an array slightly different from the original $cities array: $wine_producers = array ("America" => "Napa Valley", "Italy" => "Tuscany", "Australia" => "Rutherglen", "France" => "Loire", "Chile" => "Rapel Valley"); Sorting this array using ksort(), it would be reordered as follows: "America" => "Napa Valley" "Australia" => "Rutherglen" "Chile" => "Rapel Valley" "France" => "Loire" "Italy" => "Tuscany" 114 Gilmore_05 12/5/00 10:23 AM Page 115 Arrays Contrast this to the effects of sorting $wine_producers using sort(): "America" => "Napa Valley" "Australia" => "Tuscany" "Chile" => "Rutherglen" "France" => "Loire" "Italy" => "Rapel Valley" Less than optimal results! krsort() The krsort() function performs the same operations as ksort(), except that the key values are sorted in reverse order Its syntax is: void krsort (array $array) Sorting $wine_producers using krsort(): $wine_producers = array ("America" => "Napa Valley", "Italy" => "Tuscany", "Australia" => "Rutherglen", "France" => "Loire", "Chile" => "Rapel Valley"); krsort($wine_producers); yields the following reordering of $wine_producers: "Italy" => "Tuscany" "France" => "Loire" "Chile" => "Rapel Valley" "Australia" => "Rutherglen" "America" => "Napa Valley" For the most part, the sorting functions presented thus far will suit your general sorting requirements However, occasionally you may need to define your own sorting criteria This is possible with PHP, through the use of its three predefined functions: usort(), uasort(), and uksort() 115 Gilmore_05 12/5/00 10:23 AM Page 116 Chapter usort() The sorting function usort() provides a way in which to sort an array based on your own predefined criteria This is possible because usort() accepts as an input parameter a function name that is used to determine the sorting order of the data Its syntax is: void usort(array array, string function_name) The input parameter array is the name of the array that you are interested in sorting, and the parameter function_name is the name of the function on which the sorting mechanism will be based To illustrate just how useful this function can be, assume that you had a long list of Greek vocabulary that you needed to learn for an upcoming history exam You wanted to sort the words according to length, so that you could study the longer ones first, saving the short ones for when you are more fatigued You could sort them according to length using usort(): Listing 5-2: Defining sorting criteria with usort() $vocab = array("Socrates","Aristophanes", "Plato", "Aeschylus", "Thesmophoriazusae"); function compare_length($str1, $str2) { // retrieve the lengths of the next two array values $length1 = strlen($str1); $length2 = strlen($str2); // Verify which string is shorter in length if ($length1 == $length2) : return 0; elseif ($length1 < $length2) : return -1; else : return 1; endif; } // call usort(), defining the sorting function compare_length() usort($vocab, "compare_length"); // display the sorted list while (list ($key, $val) = each ($vocab)) { echo "$val"; } 116 Gilmore_05 12/5/00 10:23 AM Page 117 Arrays In Listing 5-2, the function compare_length() defines how the array will be sorted, in this case by comparing the lengths of the passed in elements Note that you must define two input parameters that represent the next two array elements to be compared Furthermore, take note that these elements are implicitly passed into the criteria function once usort() is called and that all elements are passed through this function automatically The functions uasort() and uksort() are variations of usort(), each using the same syntax The function uasort() will sort according to the predefined criteria, except that the key->value correlation will remain the same The function uksort() will also sort according to the predefined criteria, except that the keys will be sorted instead of the values Other Useful Functions This section describes a few functions that are obscure enough to not have a section subtitle, but are nonetheless useful array_merge() The array_merge() function merges to N arrays together, appending each to another in the order in which they appear as input parameters The function’s syntax is: array array_merge (array array1, array array2, , array arrayN) The array_merge() function provides an easy way to merge several arrays, as shown here: $arr_1 = array ("strawberry", "grape", "lemon"); $arr_2 = array ("banana", "cocoa", "lime"); $arr_3 = array ("peach", "orange"); $arr_4 = array_merge ($arr_2, $arr_1, $arr_3); // $arr_4 = array("banana", "cocoa", "lime", "strawberry", // "grape", "lemon", "peach", "orange"); array_slice() The array_slice() function will return a piece of the array, the starting and ending points decided by the offset and optional length input parameters Its syntax is: 117 Gilmore_05 12/5/00 10:23 AM Page 118 Chapter array array_slice(array array, int offset, int [length]) There are several nuances regarding the input parameters: • If the offset is positive, the returned slice will start that far away from the beginning of the array • If the offset is negative, the returned slice will start that far away from the end of the array • If the length is omitted, the returned array will consist of everything from the offset to the end of the array • If the length is provided and is positive, the returned slice will have length elements in it • If the length is provided and is negative, the returned slice will stop length elements away from the end of the array array_splice() The array_splice() function operates somewhat like the function array_slice, except that it replaces the designated elements specified by the offset and the optional length input parameters with the elements in the optional array replacement_array Its syntax is: array_splice(array input_array, int offset, int [length], array [replacement_array]); There are several factors to keep in mind regarding the input parameters: • If offset is positive, then the first element to be removed will be offset elements away from the beginning of the array • If offset is negative, then the first element to be removed will be offset elements away from the end of the array • If length is not provided, all elements starting from offset to the end of the array will be removed • If length is provided and is positive, length elements will be removed from the array 118 Gilmore_05 12/5/00 10:23 AM Page 119 Arrays • If length is provided and is negative, elements from offset to length elements away from the end of the array will be removed • If replacement_array is not specified, then the elements from offset to the optional length will be removed from the input array • If $replacement_array is specified, it must be enclosed using the array() construct, unless $replacement_array consists of only one element A few examples are in order to fully illustrate the capabilities of this function Consider the array $pasta, below Each example will manipulate this array in a slightly different manner Remove all elements from the fifth element to the end of the array: $pasta = array_splice($pasta, 5); Remove the fifth and sixth elements from the array: $pasta = array_splice($pasta, 5, 2); Replace the third and fourth elements with new elements: $pasta = array_splice($pasta, 5, 2, array("element1", "element2")); Remove all elements from positions to (n 3): $pasta = array_splice($pasta, 5, -3); As illustrated by the preceding examples, array_splice() provides a flexible method to remove specific array elements with a minimal amount of code shuffle() The function shuffle() will sort the elements of an array in random order Its syntax is: void shuffle(array array); 119 Gilmore_05 12/5/00 10:23 AM Page 120 Chapter What’s Next? This chapter introduced arrays and the predefined array-handling functions offered by PHP In particular, the following concepts were discussed: • Creation of indexed and associative arrays • Multidimensional arrays • Display of multidimensional arrays • Locating array elements • Adding and removing elements • Array size • Sorting arrays • Other useful array functions Arrays provide a very convenient and flexible means for managing information in Web applications There are several instances in later chapters in which I make use of arrays to improve coding efficiency and clarity Chapter continues our survey of PHP’s basic functionality, discussing PHP’s object-oriented capabilities 120 Gilmore_06 12/4/00 1:05 PM Page 121 C H A P TER Object-Oriented PHP If you are familiar with programming strategy, object-oriented programming (OOP) is most likely a part of your daily developmental strategy If you are new to OOP after reading this chapter and implementing a few of the examples, you will , look at coding in a whole new light This chapter focuses on OOP and PHP’s particular implementation of the OOP strategy, introducing the necessary syntax and providing examples that will allow you to begin building your own OO applications The OOP strategy can be best summed up as a shift of developmental focus from an application’s functional operations to its data structures This enables programmers to model real world objects and scenarios in the applications that they write In particular, the OOP strategy offers three advantages: • Easier to understand: OOP makes it possible to think of programs in terms of everyday objects • Improved reliability and maintenance: Designed properly, OO programs are easily expanded and modified The modular property makes it possible to independently edit various parts of the program, effectively minimizing the risk of programming errors • Faster development cycles: Modularity again plays an important role, as various parts of OO programs can be easily reused, eliminating code redundancy and ultimately resulting in the reduction of unnecessarily repeated coding errors These intrinsic advantages of OOP have resulted in major efficiency gains for developers, enabling programmers to develop more powerful, scalable, and efficient applications Many of these advantages are due to one of OOP’s foundational concepts known as encapsulation, or information hiding Encapsulation is the concept of hiding various elements in a larger entity, causing the programmer to concentrate on the larger object This results in the overall reduction of program complexity due to the diminution of unnecessary details The concept of encapsulation can be correlated to the typical driver’s operation of a car Most drivers are oblivious to the actual mechanical operations of the automobile, yet are capable of operating the vehicle exactly in the way it was intended to be operated Knowledge of the inner-workings of the engine, brakes, 121 Gilmore_06 12/4/00 1:05 PM Page 122 Chapter and steering is unnecessary, because proper interfacing has been provided to the driver that makes these otherwise highly complex operations automated and easy The same idea holds true with encapsulation and OOP, as many of these “inner workings” are hidden from the user, allowing the user to focus on the task at hand OOP makes this possible through the use of classes, objects, and various means of expressing hierarchical relationships between data entities (Classes and objects are discussed shortly.) PHP and OOP Although PHP offers general object-oriented features, it is not yet a full-featured OO language, like C++ or Java, for example Unlike OOP, PHP does not explicitly offer the following object-oriented characteristics: • Multiple inheritance • Constructor chaining (you must call a parent class constructor explicitly if you would like it to execute on construction of a derived class object) • Class abstraction • Method overloading • Operator overloading (because PHP is a loosely typed language; see Chapter 2, “Variables and Data Types,” for more info) • Concepts of private, virtual, and public • Destructors • Polymorphism However, even without these important OO features, you can still benefit from using those OO features that PHP does support PHP’s OO implementation can aid tremendously in packaging your programming functionality Read on to learn more Classes, Objects, and Method Declarations The class is the syntactical foundation of object-oriented programming and can be considered a container of sorts that holds an interrelated set of data and the 122 Gilmore_06 12/4/00 1:05 PM Page 123 Object-Oriented PHP data’s corresponding functions, better known as methods (discussed shortly) A class is a template from which specific instances of the class may be created and used in a program These instances are also known as objects One way to grasp the relationship between classes and objects is to consider the class as a general blueprint for a structure From this blueprint, several structures (or objects) can be built, each sharing the same set of core characteristics (for example, one door, two windows, and a wall thickness) However, each structure is independent of the others in the sense that it is free to change the characteristic values without affecting the values of the others (For example, one structure might have a wall thickness of five inches, while another has a wall thickness of ten inches.) The important thing to keep in mind is that they all share this characteristic of wall thickness A class can also be thought of as a data type (discussed in Chapter 2), much as one would consider a variable entitled $counter to be of type int, or a variable entitled $last_name to be of type string One could simultaneously manipulate several objects of type class just as one manipulates several variables of type int The general format of a PHP class is shown in Listing 6-1 Listing 6-1: PHP class declaration structure class Class_name { var $attribute_1; var $attribute_N; function function1() { } function functionN() { } } // end Class_name To summarize Listing 6-1, a class declaration must begin with the keyword class, much like a function declaration begins with the keyword function Each attribute declaration contained in a class must be preceded by the keyword var An attribute can be of any PHP-supported data type and should be thought of as a variable with minor differences, as you will learn throughout the remainder of this chapter Following the attributes are the method declarations, which bear a close resemblance to typical function declarations 123 ... merges to N arrays together, appending each to another in the order in which they appear as input parameters The function’s syntax is: array array_merge (array array1, array array2, , array arrayN)... 12/5/00 10: 23 AM Page 100 Chapter // $great_labels = array ("Australia", "France", "Austria"); $great_labels = array_keys($great_wines, "Clarendon Hills 96"); // $great_labels = array("Australia");... = array ("Spanish", "English", "French", // "Russian", "German", "Gaelic"); $a_ language = array_pop ($languages); // $a_ language = "Gaelic" $a_ language = array_pop ($languages); // $a_ language

Ngày đăng: 09/08/2014, 12:22