Tải bản đầy đủ - 0 (trang)
Chapter 4. Introduction to Object-Oriented Programming with PHP 5

Chapter 4. Introduction to Object-Oriented Programming with PHP 5

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

4.1ClassesandObjects

Thebasicideaofobject-orientedprogrammingistobinddata

andfunctionsinconvenientcontainerscalledobjects.For

instance,inChapter7we'llshowyouhowtostandardizethe

lookofyourownwebpagesthroughanobjectcalleda

template.YourPHPcodecanrefertothisobjectthrougha

variable;we'llassumehereyou'vedecidedtocallthevariable

$template.Allthecompleximplementationoftemplatesis

hidden:youjustloadintheproperpackageandissueaPHP

statementsuchas:

$template=newHTML_Template_IT("./templates");



Asthestatementsuggests,you'vejustcreatedanewobject.

Theobjectiscalled$templateandisbuiltbythe

HTML_Template_ITpackageapackagewhosecodeyoudon't

needtoknowanythingabout.Onceyouhaveatemplateobject,

youcanaccessthefunctionalityprovidedbythe

HTML_Template_ITpackage.

Aftervariousmanipulationsofthe$templateobject,youcan

inserttheresultsintoyourwebpagethroughthePHP

statement:

$template->show();



Thesyntaxofthisstatementisworthexamining.Asthe

parenthesesindicate,show()isafunction.Howeverthe->

operatorassociatesshow()withtheobjectvariable$template.

Whenthefunctionshow()iscalled,itusesthedatathatisheld



bythe$templateobjecttocalculatearesult:putanotherway,

show()iscalledonthe$templateobject.

Thefunctionsthatyoucancalldependonthesupportprovided

bythepackagetheshow()functionisprovidedbythe

HTML_Template_ITpackageandcanbecalledon

HTML_Template_ITobjectssuchas$template.Intraditional

object-orientedparlance,show()iscalledamethodormember

functionoftheHTML_Template_ITobject.

HTML_Template_ITiscalledaclassbecauseyoucanuseitto

createmanysimilartemplateobjects.Eachtimeyouissuea

newstatementyouaresaidtocreateaninstanceoftheclass.

Thus,the$templateobjectisaninstanceofthe

HTML_Template_ITclass.

We'veshownhowtouseobjectscreatedbyotherpackages.

However,tounderstandobjectsbetter,it'stimetodefineaclass

ofourown.Example4-1showsasimpleclassinventedforthe

purposesofthischapterthat'scalledUnitCounter.The

UnitCounterclassprovidestwotrivialfeatures:wecanusea

UnitCounterobjecttokeepacountofthings,andtocalculate

thetotalweightofthethingswehavecounted.Laterinthis

chapter,andinChapter14weusetheUnitCounterclass,

togetherwithotherclasses,todevelopasimplefreight-cost

calculator.

Example4-1showshowtheclassUnitCounterisdefinedusing

theclasskeyword.TheUnitCounterclassdefinestwomember

variables$unitsand$weightPerUnit,andtwofunctionsadd(

)andtotalWeight().Collectively,thevariablesandthe

functionsaremembersoftheclassUnitCounter.



Example4-1.Definitionoftheuser-definedclass

UnitCounter






//DefinitionoftheclassUnitCounter

//

classUnitCounter

{

//Membervariables

var$units=0;

var$weightPerUnit=1.0;



//Add$ntothetotalnumberofunits,default$nto1

functionadd($n=1)

{

$this->units=$this->units+$n;

}



//Memberfunctionthatcalculatesthetotalweight

functiontotalWeight()



{

return$this->units*$this->weightPerUnit;

}

}



?>



Theclassdefinitiondefineshowdataandfunctionalityare

actuallyboundtogethermembervariablesandfunctionstake

theirmeaningfromtheclassofwhichthey'reapart.Theclass

definitionshowninExample4-1doesnotactuallyrunanycode

orproduceanyoutput.Insteadaclassdefinitioncreatesanew

datatypethatcanbeusedinaPHPscript.Inpractice,you

mightsavetheclassdefinitioninanincludefile,andinclude

thatfileintoanyscriptthatmakesuseoftheclass.

Tousethemembervariablesandfunctionsdefinedinaclass,

aninstanceoftheclassorobjectneedstobecreated.Like

otherdatatypessuchasintegers,strings,orarrays,objects

canbeassignedtovariables.However,unlikeothertypes,

objectsarecreatedusingthenewoperator.Anobjectofclass

UnitCountercanbecreatedandassignedtoavariableas

follows:

//CreateanewUnitCounterobject

$bottles=newUnitCounter;



Unlikevariablenames,classnamesinPHParenotcase

sensitive.Whilewestartallourclassnameswithanuppercase

letter,UnitCounter,unitcounter,andUNITCOUNTERallreferto

thesameclass.

OnceanewUnitCounterobjectiscreatedandassignedtothe

$bottlesvariable,themembervariablesandfunctionscanbe

used.Membersoftheobject,bothvariablesandfunctions,are

accessedusingthe->operator.The$unitsmembervariable

canbeaccessedas$bottles->unitsandusedlikeanyother

variable:

//setthecounterto2dozenbottles

$bottles->units=24;



//prints"Thereare24units"

print"Thereare{$bottles->units}units";



Toincludethevalueofanobject'smembervariablesina

double-quotedstringliteral,thebracessyntaxisused.String

literalsandthebracessyntaxarediscussedinChapter2.

Theadd()memberfunctioncanbecalledtooperateonthe

$bottlesvariablebycalling$bottles->add().Thefollowing

fragmentincreasesthevalueof$bottles->unitsby3:

//Addthreebottles

$bottles->add(3);



//prints"Thereare27units"

print"Thereare{$bottles->units}units";



Manyobjectsofthesameclasscanbecreated.Forexample,

youcanusethefollowingfragmenttocreatetwoUnitCounter

objectsandassignthemtotwovariables:

//CreatetwoUnitCounterobjects

$books=newUnitCounter;

$cds=newUnitCounter;



//Addsomeunits

$books->add(7);

$cds->add(10);



//prints"7booksand10CDs"

print"{$books->units}booksand{$cds->units}CDs";



Boththe$booksand$cdvariablesreferenceUnitCounter

objects,buteachobjectisindependentoftheother.



4.1.1MemberVariables

MembervariablesareavailableinPHP4andPHP5.

Membervariablesaredeclaredaspartofaclassdefinitionusing

thevarkeyword.Membervariablescanalsobedefinedwiththe

privateandprotectedkeywordsaswedescribelaterinthe

chapter.Membervariablesholdthedatathatisstoredinan

object.

Theinitialvalueassignedtoamembervariablecanbedefined

intheclassdefinition.TheUnitCounterclassdefinedinExample

4-1setsinitialvaluesforbothmembervariables:

var$units=0;

var$weightPerUnit=1.0;



Thevarkeywordisrequiredtoindicatethat$unitsand

$weightPerUnitareclassmembervariables.Whenanew

UnitCounterobjectiscreated,theinitialvaluesof$unitsand

$weightPerUnitaresetto0and1.0respectively.Ifadefault

valueisnotprovidedintheclassdefinition,thenthemember

variableisnotsettoanyvalue.

Youdon'thavetoexplicitlydeclaremembervariablesaswe

haveinExample4-1.However,werecommendthatyoualways

declarethemandsetaninitialvaluebecauseitmakestheinitial

stateofthevariablesobvioustousersofyourcode.



4.1.2MemberFunctions

MemberfunctionsareavailableinPHP4andPHP5.



Memberfunctionsaredefinedaspartoftheclassdefinitionthe

UnitCounterclassdefinedinExample4-1includestwomember

functionsadd()andtotalWeight().Boththesefunctionsaccess

themembervariablesoftheobjectwiththespecialvariable

$this.Thevariable$thisisspecialbecausePHPusesitasa

placeholderuntilarealobjectiscreated.Whenamember

functionisrun,thevalueof$thisissubstitutedwiththeactual

objectthatthefunctioniscalledon.Considerthe

implementationoftheadd()memberfunctionofUnitCounter

fromExample4-1:

//Add$ntothetotalnumberofunits,default$nto1if

//noparametersarepassedtoadd()

functionadd($n=1)

{

$this->units=$this->units+$n;

}



Thefunctionaddsthevalueoftheparameter$ntothemember

variable$this->units.Ifnoparameterispassed,$ndefaults

to1.Whentheadd()functioniscalledonthe$bottlesobject

inthefollowingexample,

//CreateanewUnitCounterobject

$bottles=newUnitCounter;



//Calltheadd()function



$bottles->add(3);



theplaceholder$thisintheadd()functionactsastheobject

$bottles.

ThetotalWeight()memberfunctionalsoaccessesmember

variableswiththe$thisplaceholder:thefunctionreturnsthe

totalweightbymultiplyingthevalueofthemembervariables

$this->unitsand$this->weightPerUnit.

//CreateanewUnitCounterobject

$bricks=newUnitCounter;



$bricks->add(15);



//Prints15-15unitsat1Kgeach

print$bricks->totalWeight();



PHP5allowstheresultofamemberfunctiontobeincludedinto

astringliteralusingthebracessyntax.Thefollowingfragment

showshow,andshowsanalternativethatcanbeusedwith

PHP4:

//ThislineonlyworksforPHP5

print"totalweight={$bottles->totalWeight()}kg";



//ThisworksforbothPHP4andPHP5

print"totalweight=".$bottles->totalWeight()."kg";



4.1.3UsingincludeFilesforClassDefinitions

ByplacingthedefinitioninExample4-1intoafileforexample

UnitCounter.incyoucanincludeorrequiretheUnitCounterclass

inotherscripts.Example4-2usestherequiredirectiveto

includetheUnitCounterclassdefinition.



Example4-2.UsingtheUnitCounterclass




"http://www.w3.org/TR/html401/loose.dtd">








UsingUnitCounter








require"UnitCounter.inc";



//CreateanewUnitCounterobject

$bottles=newUnitCounter;



//setthecounterto2dozenbottles

$bottles->units=24;



//Addasinglebottle

$bottles->add();



//Addthreemore

$bottles->add(3);



//Showthetotalunitsandweight

print"Thereare{$bottles->units}units,";



print"totalweight=".$bottles->totalWeight()."kg";



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

Chapter 4. Introduction to Object-Oriented Programming with PHP 5

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

×