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

PHP 5/MySQL Programming- P56 docx

5 212 0
Tài liệu đã được kiểm tra trùng lặp

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 5
Dung lượng 115,41 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The basic technique for creating methods is to build a function within the con-text of a class definition.. Most often you use the con-structor to initialize your properties, so I do tha

Trang 1

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 Critterclass

so it has methods with which to manipulate the nameproperty 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

j e

Trang 2

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 Critterclass:

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 constructpreceded by two underscores.)

254

g r

s o

l u

g in

e r

FIGURE 7.9

This Critter can

change his name

on-the-fly.

Trang 3

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 nameproperty

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 methodsusually 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

T R A P

255

j e

Trang 4

Building a Getter Method to Retrieve Property Values

It’s also good to have methods that return property values These methods are called gettermethods, 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.

T R I C K

256

g r

s o

l u

g in

e r

Trang 5

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 Critterclass 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 Critterdefinition 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 phptags 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

j e

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