PHP 5/MySQL Programming- P56 docx

5 212 0
PHP 5/MySQL Programming- P56 docx

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

Thông tin tài liệu

Adding Methods to a Class To make a class really interesting, it needs to have some sort of behavior as well as data. This is where methods come in. I’ll improve on the simple Critter class so it has methods with which to manipulate the name property. Here’s the new code, found in methods.php: <!doctype html public “-//W3C//DTD HTML 4.0 //EN”> <html> <head> <title>Critter</title> </head> <body> <? // Adding methods //define the critter class class Critter{ var $name; function __construct($handle = “anonymous”){ $this->name = $handle; } // end constructor function setName($newName){ $this->name = $newName; } // end setName function getName(){ return $this->name; } // end getName } // end Critter class //make an instance of the critter $theCritter = new Critter(); //print original name print “Initial name: “ . $theCritter->getName() . “<br>\n”; 253 C h a p t e r 7 W r i t i n g P r o g r a m s w i t h O b j e c t s print “Changing name <br>\n”; $theCritter->setName(“Melville”); print “New name: “ . $theCritter->getName() . “<br>\n”; ?> </body> </html> This code produces the output indicated in Figure 7.9. The basic technique for creating methods is to build a function within the con- text of a class definition. That function then becomes a method of the class. Building a Constructor The first function defined in most classes is called the constructor . Constructors are special methods used to build an object. Any code you want to occur when the object first appears should go in the constructor. Most often you use the con- structor to initialize your properties, so I do that for the Critter class: function __construct($handle = “anonymous”){ $this->name = $handle; } // end constructor To specify that a function is a class constructor, it should be called __construct. (That’s construct preceded by two underscores.) 254 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r FIGURE 7.9 This Critter can change his name on-the-fly. The __construct name for constructors was added in PHP 5.0. If you have an earlier version of PHP, the constructor will have the same name as the class, but is still a function defined within the class. The constructor is often used to initialize properties—in this case the name property. Notice that the constructor accepts a parameter. If you want to make a parameter optional in any PHP function, assign a default value to the parameter, as I have done here. This is a sneaky way that PHP achieves polymorphism. Creating a Property Setter The setName() method is an example of a property access method that allows you to change a property through a method. The code for setName() is pretty clean: function setName($newName){ $this->name = $newName; } // end setName Setter methods usually begin with set and they always accept a parameter. The parameter is the value the user wants to change. Inside the method, I modify the actual instance variable associated with the name property. Access methods are useful because I can do a number of things to test the information before I make any property changes. For example, if I decided that all my critter names should be fewer than five characters, I could modify setName() to enforce that rule. function setName($newName){ if(strlen($newName) > 5){ $newName = substr($newName, 0, 5); } // end if $this->name = $newName; } // end setName This is a trivial example, but access methods can do a lot to prevent certain kinds of problems. For example, if your program is expecting numeric input and gets a string instead, your access method can quietly (or not-so-quietly, if you wish) change the value to something legal without the program crashing. Use of access methods can be a splendid way to add polymorphism to your classes. If you are using a class that has access methods, you should always use them rather than directly modifying a property. If you directly modify a property, you are circum- venting the safety net provided by the access method. TRAP 255 C h a p t e r 7 W r i t i n g P r o g r a m s w i t h O b j e c t s Building a Getter Method to Retrieve Property Values It’s also good to have methods that return property values. These methods are called getter methods, and they are usually very straightforward, such as this one: function getName(){ return $this->name; } // end getName The getName() method simply returns the value of the appropriate property. This is useful because you might have different ways of returning the same value. Some- times you might have a getter for a property that doesn’t actually exist! For exam- ple, if you were creating a circle class, it might have setRadius(), getRadius(), getArea(), and getCircumference() methods. The user should be able to read and write the circle’s radius and should be able to read the circumference and area. These values aren’t actually stored in the class, because they are derived from the radius. The programmer using the class doesn’t have to know or care about this, but simply knows that some properties are read/write and some are read only. Using Access Methods to Manipulate Properties With getter and setter methods in place, it’s easy to manipulate an object’s prop- erties. //make an instance of the critter $theCritter = new Critter(); //print original name print “Initial name: “ . $theCritter->getName() . “<br>\n”; print “Changing name <br>\n”; $theCritter->setName(“Melville”); print “New name: “ . $theCritter->getName() . “<br>\n”; Anytime I want to change the name, I invoke the setName() method. To retrieve the name, I use the getName() method. Note that the terms get and set make sense in the context of the programmer using the class, not the programmer designing the class. The target audience for most objects is programmers rather than the general public. You’re writing code to make a programmer’s job easier. TRICK 256 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r Inheriting from a Parent Class You’ve seen encapsulation and polymorphism. The third pillar of OOP is a con- cept called inheritance. Inheritance is used to build on previous work and add new features to it. It is used to build common functionality and at the same time allow variation. In writing a game using Critters, for example, I define all the characteristics com- mon to everything in the base Critter class and then add a bunch of subclasses for the various types. These subclasses incorporate additions or deviations from the basic behavior. Think again of the police car I mentioned earlier in this chap- ter. The car is a base class while a police car is an extension of the base class. I’ll take the Critter definition and put it in its own file, like this: <? // Critter definition //define the critter class class Critter{ var $name; function __construct($handle = “anonymous”){ $this->setname($handle); } // end constructor function setName($newName){ $this->name = $newName; } // end setName function getName(){ return $this->name; } // end getName } // end Critter class ?> Notice there’s no HTML and no code that uses the class. This file simply contains the definition for the class inside the normal php tags. Once I’ve got the class def- inition safely stored in a file, I can reuse it easily. I made one minor but useful 257 C h a p t e r 7 W r i t i n g P r o g r a m s w i t h O b j e c t s . can change his name on-the-fly. The __construct name for constructors was added in PHP 5.0. If you have an earlier version of PHP, the constructor will have the same name as the class, but is still a. you want to make a parameter optional in any PHP function, assign a default value to the parameter, as I have done here. This is a sneaky way that PHP achieves polymorphism. Creating a Property. has methods with which to manipulate the name property. Here’s the new code, found in methods .php: <!doctype html public “-//W3C//DTD HTML 4.0 //EN”> <html> <head> <title>Critter</title> </head> <body> <? //

Ngày đăng: 07/07/2014, 02:20

Mục lục

  • PHP 5 / MySQL Programming for the Absolute Beginner

    • Cover

    • Contents

    • Introduction

    • Chapter 1: Exploring the PHP Environment

    • Chapter 2: Using Variables and Input

    • Chapter 3: Controlling Your Code with Conditions and Functions

    • Chapter 4: Loops and Arrays

    • Chapter 5: Better Arrays and String Handling

    • Chapter 6: Working with Files

    • Chapter 7: Writing Programs with Objects

    • Chapter 8: XML and Content Management Systems

    • Chapter 9: Using MySQL to Create Databases

    • Chapter 10: Connecting to Databases within PHP

    • Chapter 11: Data Normalization

    • Chapter 12: Building a Three-Tiered Data Application

    • Index

    • Team DDU

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

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

Tài liệu liên quan