Tải bản đầy đủ - 0 (trang)
Chapter 14. Advanced Features of Object-Oriented Programming in PHP 5

Chapter 14. Advanced Features of Object-Oriented Programming in PHP 5

Tải bản đầy đủ - 0trang

14.1WorkingwithClassHierarchies

InChapter4,weshowedyouhowinheritancecanbeusedasa

powerfultoolinobject-orientedprogramming.Usingthe

extendskeyword,aclasscaninheritthecapabilitiesfroma

parentclass.AsweexplainedinChapter4,PHPallowsan

inheritancefromonlyoneparentclass,butaclasscanbe

extendedtocreateanynumberofchildclasses.

Inheritanceallowsfunctionalitytobebuiltupfromrelated

classes.Eachclassprovidesspecializedsupportthat'sspecific

toaclass'spurpose.It'scommonthatfunctionalityinanobjectorientedapplicationisprovidedbyclasshierarchiesratherthan

single,unrelatedclasses.

Example14-1showshowaclasshierarchyisformedtoprovide

functionalitythatdescribesshapes.



Example14-1.Shapeclasses




classShape

{

var$color;

var$sides;



functioncolor()

{

return$this->color;

}



functionsides()

{

return$this->sides;

}



function__construct($color,$sides)

{

$this->color=$color;

$this->sides=$sides;

}

}



classCircleextendsShape

{



function__construct($color)

{

parent::__construct($color,1);

}

}



classPolygonextendsShape

{

var$angles;



functionangles()

{

return$this->angles;

}



function__construct($color,$sides)

{



parent::__construct($color,$sides);

$this->angles=$sides;

}

}



classTriangleextendsPolygon

{

function__construct($color)

{

parent::__construct($color,3);

}

}



classRectangleextendsPolygon

{

function__construct($color)

{

parent::__construct($color,4);

}



}



?>



TheclassShapedefinedintheExample14-1supportsonlytwo

features:thecolorandnumberofsidesofashape.TheCircle

andPolygonclassesbothextendthebaseShapeclass:the

Circleconstructorfunctionalwayssetsthenumberofsidesto1,

[1]

whilethePolygonclassallowsanarbitrarynumberofsides

anddefinesthememberfunctionangles()thatreturnsthe

numberofanglestheshapemakes.

[1]Thenumberofsidesofacircledependsonyourdefinitionofsidesomedefinitionsleadtono

sides,sometoaninfinitenumber.Byourdefinition,acirclehasoneside.



ThePolygonclassisextendedbytheTriangleandRectangle

classes,andeachdefinesaconstructorfunctionthatsetsthe

appropriatenumberofsides.Therelationshipbetweenthe

classesdefinedinExample14-1isshownintheclassdiagram

inFigure14-1.



Figure14-1.ClasshierarchyfortheShapeclasses



TheclassesdefinedinExample14-1aren'tparticularlyusefulwe

keptthefunctionalitytoaminimumtoillustratehowa

hierarchyisformed.Arealapplicationthatdealswithshapes

woulddefinemembervariablesandfunctionstosupportthe

applicationrequirements.Forexample,ifyouwereinterestedin

thesizeofashape,youcouldaddmembervariablestorecord

thedimensions,andfunctionsthatcalculatethearea.



14.1.1Polymorphism

Whileaclasshierarchycanhelpyoutodevelopmodularcode,

mostofthepowerofobject-orientedprogrammingcomesfrom

theabilitytouseanobjectdifferentlyindifferent

circumstances,acapabilityknownaspolymorphism.Consider

theobjectsthatwecancreatefromtheclassesdefinedin

Example14-1.Thefollowingfragmentcreatesanarrayof

objectsusingtheCircle,Triangle,andRectangleclasses;and

thenprintsinformationabouteachshapeusingaforeachloop.

//Createanarrayofobjects

$shapes=array(

newTriangle("blue"),

newCircle("green"),

newRectangle("red"));



foreach($shapesas$s)



print"Ihavea{$s->color()}shapewith{$s->sides()}si



Wecancallthecolor()andsides()memberfunctionsoneach

oftheobjectsinthepreviousexamplebecauseeachobject,

throughinheritance,isaShape.Wecan'tcalltheangles()

functiononeachobjectbecausenotalloftheobjectsare

PolygonsandonlyinstancesofPolygonshavetheangles()

memberfunction.Thepreviousexampleprints:

Ihaveablueshapewith3sides

Ihaveagreenshapewith1sides

Ihavearedshapewith4sides



Wegivefurtherexamplesthatshowthebenefitsofpolymorphic

behaviorlaterinthischapter.



14.1.2DiscoveringRelationships

TheinstanceofkeywordisavailableinPHP5,andtheis_a(),

get_class(),andget_parent_class()functionsareavailablein

PHP4andPHP5.

Whenyou'redealingwithanobjectinaPHPscript,it'snot

alwaysobviouswhattypeofobjectitis.Forexample,whileall

theobjectswecreatedinthepreviousexampleareShapes,

onlytheTriangleandRectangleobjectscanbeusedasPolygon

objects.PHP5supportstheinstanceofoperatorthatallows

youtowritescriptsthatcantestthecapabilitiesofanobject

beforeusingit.Thefollowingfragmentshowshoweachshape

objectistestedbeforeanattemptismadetocallthePolygon



memberfunction:

//Createanarrayofobjects

$shapes=array(

newTriangle("blue"),

newCircle("green"),

newRectangle("red"));



foreach($shapesas$s)

{

if($sinstanceofPolygon)



print"Ihavea{$s->color()}polygonwith{$s->sides(

sidesand{$s->angles()}internalangles\n";

else



print"Ihavea{$s->color()}shapewith{$s->sides()

}



ThepreviousexampleprintsthelongerPolygonmessagefor

theTriangleandRectangleobjects,andtheshorterShape

messagefortheCircleobject:.

Ihaveabluepolygonwith3



sidesand3internalangles

Ihaveagreenshapewith1sides

Ihavearedpolygonwith4

sidesand4internalangles



14.1.2.1Functions

TheinstanceofkeywordperformsasimilarfunctiontothePHP

libraryfunctionis_a().Bothevaluatetotrueiftheobjectisan

instanceofthetestclass,oranancestorclass.Here'san

examplethatusesis_a()toperformthesamefunctionasin

thepreviousexample:

if(is_a($s"Polygon"))



print"Ihavea{$s->color()}polygonwith{$s->sides(

sidesand{$s->angles()}internalangles\n";

else



print"Ihavea{$s->color()}shapewith{$s->sides()



PHPprovidesseveralrelatedfunctionsthatreturninformation

abouttheclasshierarchyofanobject:

booleanis_subclass_of(objectobj,stringclassname)

stringget_class(objectobj)



stringget_parent_class(objectobj)

Thefunctionis_subclass_of()returnstrueiftheclassofobject

objisadescendantofclassname.Theget_class()function

returnsthenameoftheclassfortheobjectobj,and

get_parent_class()returnstheparentclassname.Both

get_class()andget_parent_class()normalizethenameofthe

classtolowercaseasdemonstratedinthefollowingfragment:

//CreateanewTriangleobject

$shape=newTriangle("orange");



//prints"triangle"

printget_class($shape);



//prints"polygon"

printget_parent_class($shape);



14.2ClassTypeHints

TheclasstypehintfeatureisavailableinPHP5.

PHPisalooselytypedlanguage,andthisallowsdifferenttypes

ofdatatobepassedasparametersintofunctions.Whenuserdefinedfunctionsorclassmemberfunctionsaredesignedto

workwithobjectparameters,itisoftenusefultocheckthetype

ofobjectbeforeitisused.PHP5allowsyoutospecifythetype

ofobjectparameterwithaclasstypehint.Considerthe

followingexamplethatdefinesafunctiontoreturninformation

aboutShapeobjects:



//User-definedfunctionthatreturnsinformationaboutaShape

//object

functionshapeInfo(Shape$shape)

{



return"Ihavea{$s->color()}shapewith{$s->sides()}s

}



ThedefinitionofthefunctionshapeInfo()includestheclass

typehintShapebeforetheparameter$shape.Thisinstructs

PHPtochecktheclassof$shapewhenthescriptisrun.Ifthe

functioniscalledwithanobjectthatisnotaShape,orevena

valuethatwasnotanobject,PHPcausesthescripttoterminate

withafatalerror.

Usingclasstypehintsistheequivalentofcheckingthe

parameterwiththeinstanceofkeyword.Usingthisapproach,



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 14. Advanced Features of Object-Oriented Programming in PHP 5

Tải bản đầy đủ ngay(0 tr)

×