SAMS Teach Yourself PHP4 in 24 Hours phần 4 docx

45 347 0
SAMS Teach Yourself PHP4 in 24 Hours phần 4 docx

Đ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

136 foreach ( $this->headers as $header ) print "<B>$header</B> "; print "\n"; foreach ( $this->table_array as $y ) { foreach ( $y as $xcell ) print "$xcell "; print "\n"; } print "</pre>"; } This code fragment should be fairly self-explanatory. We loop first through the headers array property, writing each element to the screen. We then do the same for the table_array property. Because the table_array property is a two-dimensional array, each of its elements is itself an array that must be looped through within the main loop. Bringing It All Together Listing 8.5 includes the entire Table class, as well the code that instantiates a Table object and calls each of its methods. Listing 8.5: The Table Class 1: <html> 2: <head> 3: <title>Listing 8.5</title> 4: </head> 5: <body> 6: <?php 7: class Table 8: { 9: var $table_array = array(); 10: var $headers = array(); 137 11: var $cols; 12: function Table( $headers ) 13: { 14: $this->headers = $headers; 15: $this->cols = count ( $headers ); 16: } 17: 18: function addRow( $row ) 19: { 20: if ( count ($row) != $this->cols ) 21: return false; 22: array_push($this->table_array, $row); 23: return true; 24: } 25: 26: function addRowAssocArray( $row_assoc ) 27: { 28: $row = array(); 29: foreach ( $this->headers as $header ) 30: { 31: if ( ! isset( $row_assoc[$header] )) 32: $row_assoc[$header] = ""; 33: $row[] = $row_assoc[$header]; 34: } 35: array_push($this->table_array, $row); 36: return true; 37: } 38: 39: function output() 40: { 138 41: print "<pre>"; 42: foreach ( $this->headers as $header ) 43: print "<B>$header</B> "; 44: print "\n"; 45: foreach ( $this->table_array as $y ) 46: { 47: foreach ( $y as $xcell ) 48: print "$xcell "; 49: print "\n"; 50: } 51: print "</pre>"; 52: } 53: } 54: 55: $test = new table( array("a","b","c") ); 56: $test->addRow( array(1,2,3) ); 57: $test->addRow( array(4,5,6) ); 58: $test->addRowAssocArray( array ( b=>0, a=>6, c=>3 ) ); 59: $test->output(); 60: ?> 61: </body> 62: </html> You can see the output of Listing 8.5 in Figure 8.1. 139 Figure 8.1: The Table object in action. The output looks neat as long as the individual strings are the same length. This will change if we vary the length of any of the elements. What's Missing? Although this class will do a job effectively for us, with more time and space, we might have added some features and safeguards. Because PHP is loosely typed, it is our responsibility to make sure that parameters passed to our methods are the type we are expecting. For this purpose, we can use the data functions covered in Hour 16, "Working with Data." We might also want to make the Table object a little more flexible, adding methods to sort the rows according to the values in any column before we output, for example. Why a Class? So, what's better about using an object to achieve this task than simply manipulating arrays ourselves as and when we need to? It certainly isn't efficiency. We've added overheads to the process of storing and retrieving information. First, this code is reusable. It has a clear purpose— to represent data in a certain way, and we can now slot it into any project that needs data stored and output in this way. Second, a Table object is active. We can ask it to output its data without bothering to write code to loop through its table_array property. 140 Third, we've built an interface to the object's functionality. If we decide later to optimize the code in the class, we can do so without disturbing the rest of the project, as long as the same methods remain, expecting the same arguments and returning the same data types. Finally, we can build classes that inherit, extend, and override its functionality. This makes object-oriented code truly cool. Inheritance To create a class that inherits functionality from a parent class, we need to alter our class declaration slightly. Listing 8.6 returns to our simple example. Listing 8.6: Creating a Class That Inherits from Another 1: <html> 2: <head> 3: <title>Listing 8.6</title> 4: </head> 5: <body> 6: <?php 7: class first_class 8: { 9: var $name = "harry"; 10: function first_class( $n ) 11: { 12: $this->name = $n; 13: } 14: function sayHello() 15: { 16: print "Hello my name is $this->name<br>"; 17: } 18: } 19: 20: class second_class extends first_class 141 21: { 22: 23: } 24: 25: $test = new second_class("son of harry"); 26: $test->sayHello(); 27: // outputs "Hello my name is son of harry" 28: ?> 29: </body> 30: </html> In addition to the simple first_class class, we have created an even more basic second_class class. Notice the extends clause in the class declaration. This means that a second_class object inherits all the functionality laid down in the first_class class. Any second_class object will have a sayHello() method and a name property just as any first_class object would. If that's not enough, there's even more magic to be found in Listing 8.6. Notice that we didn't define a constructor method for the second_class class. So, how was the name property changed from the default, "harry" to the value passed to the second_class class, "son of harry"? Because we didn't provide a constructor, the first_class class's constructor was automatically called. Note If a class extending another doesn't contain a constructor method, the parent class's constructor method will be called automatically when a child object is created. This feature is new in PHP4. Overriding the Method of a Parent Class The second_class class currently creates objects that behave in exactly the same way as first_class objects. In object-oriented code, child classes can override the methods of their parents, allowing objects instantiated from them to behave differently, while otherwise retaining much of the same functionality. Listing 8.7 gives the second_class class its own sayHello() method. Listing 8.7: The Method of a Child Class Overriding That of Its Parent 1: <html> 142 2: <head> 3: <title>Listing 8.7</title> 4: </head> 5: <body> 6: <?php 7: class first_class 8: { 9: var $name = "harry"; 10: function first_class( $n ) 11: { 12: $this->name = $n; 13: } 14: function sayHello() 15: { 16: print "Hello my name is $this->name<br>"; 17: } 18: } 19: 20: class second_class extends first_class 21: { 22: function sayHello() 23: { 24: print "I'm not going to tell you my name<br>"; 25: } 26: } 27: 28: $test = new second_class("son of harry"); 29: $test->sayHello(); 30: // outputs "I'm not going to tell you my name" 31: ?> 143 32: </body> 33: </html> The sayHello() method in the second_class class is called in preference to that in the parent class. Calling an Overridden Method Occasionally, you will want the functionality of a parent class's method, as well as the benefit of your own additions. Object-oriented programming allows you to have your cake and eat it too. In Listing 8.8, the second_class's sayHello() method calls the method in the first_class class that it has overridden. Listing 8.8: Calling an Overridden Method 1: <html> 2: <head> 3: <title>Listing 8.8</title> 4: </head> 5: <body> 6: <?php 7: class first_class 8: { 9: var $name = "harry"; 10: function first_class( $n ) 11: { 12: $this->name = $n; 13: } 14: function sayHello() 15: { 16: print "Hello my name is $this->name<br>"; 17: } 18: } 19: 144 20: class second_class extends first_class 21: { 22: function sayHello() 23: { 24: print "I'm not going to tell you my name "; 25: first_class::sayHello(); 26: } 27: } 28: 29: $test = new second_class("son of harry"); 30: $test->sayHello(); 31: // outputs "I'm not going to tell you my name Hello my name is son of harry" 32: ?> 33: </body> 34: </html> By using the syntax parentclassname::methodname() we can call any method that we have overridden. This syntax is new to PHP4— the same code will result in a parse error with PHP3. Inheritance: An Example You've seen how one class can inherit, override, and extend the functionality of another. Now we can use some of these techniques to create a class that inherits from the Table class created in Listing 8.5. The new class will be called HTMLTable and will be designed to overcome the deficiencies of Table's output() method. Defining HTMLTable's Properties HTMLTable will format the data that it stores courtesy of Table's functionality using a standard HTML table. For this example, we will allow an HTMLTable's user to 145 change the CELLPADDING argument of the TABLE element and the BGCOLOR argument of the TD element. A real-world example should allow for many more changes than this. class HTMLTable extends Table { var $bgcolor; var $cellpadding = "2"; } We have defined a new class and established that it will inherit from Table by using the extends clause. We create two properties, bgcolor and cellpadding, giving cellpadding a default value of 2. Creating the Constructor You have already seen that a parent class's constructor is called automatically if you don't define a constructor for a child class. In this case, however, we want to do more work with our constructor than has already been written for the Table class: function HTMLTable( $headers, $bg="#ffffff" ) { Table::Table($headers); $this->bgcolor=$bg; } The HTMLTable constructor accepts an array of column names and a string. The string becomes our bgcolor property, and we give it a default value, making it an optional argument. We call the Table class's constructor, passing the $header array to it. Laziness is a virtue in programming, so we let the Table class's constructor do its thing and worry no more about it. We initialize the HTMLObject's bgcolor property. Note If a child class is given a constructor method, the parent's constructor is no longer called implicitly. The child class's constructor must explicitly call that of its parent. [...]... $row_assoc[$header] )) 34: $row_assoc[$header] = " "; 35: $row[] = $row_assoc[$header]; 36: } 37: array_push($this->table_array, $row) ; 38: } 39: 40 : function output() 41 : { 42 : print ""; 43 : foreach ( $this->headers as $header ) 44 : print "$header "; 45 : print "\n"; 46 : foreach ( $this->table_array as $y ) 47 : { 149 48 : foreach ( $y as $xcell ) 49 : print "$xcell "; 50: print "\n"; 51: } 52: print "";... form input, we now find that input from the "products[]" element will be available in an array called $products demonstrate this in Listing 9.5 Listing 9.5: Reading Input from the Form in Listing 9 .4 1: 2: 3: Listing 9.5 Reading input from the form in Listing 9 .4 4: We 159 5: 6: 10: 11: This is the first script in this book that is not designed to be called by hitting a link or typing directly into the browser's location field We include the code from Listing 9.3 in a file called eg9.3.php This file... company intranet uses a subset of XML; could this be accommodated too? At this stage, including all the functionality in a single class is beginning to look a little unwieldy, and you would already be considering a complete rewrite of the code Let's try this scenario out with our Table and HTMLTable examples We have already substantially separated formatting the data from acquiring and preparing it... bunch of them into an array When we're ready, we can loop through the lot, calling output() without worrying about the mechanics From a single array of Table-derived objects, we can write emails, HTML, XML, or plain text, simply by repeatedly calling output()! Summary It is not possible to introduce you to all the aspects of object-oriented programming in one short hour, but I hope I have introduced you . as $header ) 43 : print "<B>$header</B> "; 44 : print " "; 45 : foreach ( $this->table_array as $y ) 46 : { 47 : foreach ( $y as $xcell ) 48 : print "$xcell. "<pre>"; 43 : foreach ( $this->headers as $header ) 44 : print "<B>$header</B> "; 45 : print " "; 46 : foreach ( $this->table_array as $y ) 47 : { 149 48 :. enforcing privacy in PHP4. function setCellpadding( $padding ) { $this->cellpadding = $padding; } The Output() Method The Output() method completely overrides the equivalent method in

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

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan