Documente Academic
Documente Profesional
Documente Cultură
AdvertiseHere
ObjectOrientedPHPforBeginners
JasonLengstorfonDec23rd2011with202comments
TutorialDetails
Program:PHP
Version(ifapplicable):PHP5+
Difficulty:Intermediate
EstimatedCompletionTime:2Hours
Twiceamonth,werevisitsomeofourreaders favoritepostsfromthroughoutthehistoryofNettuts+.ThistutorialwasfirstpublishedinJuly,2010.
FormanyPHPprogrammers,objectorientedprogrammingisafrighteningconcept,fullofcomplicatedsyntaxandotherroadblocks.Asdetailedinmybook,Pro
PHPandjQuery,you lllearntheconceptsbehindobjectorientedprogramming(OOP),astyleofcodinginwhichrelatedactionsaregroupedintoclassestoaid
increatingmorecompact,effectivecode.
UnderstandingObjectOrientedProgramming
Objectorientedprogrammingisastyleofcodingthatallowsdeveloperstogroupsimilartasksintoclasses.Thishelpskeepcodefollowingthetenetdon trepeat
yourself(DRY)andeasytomaintain.
Objectorientedprogrammingisastyleofcodingthatallowsdeveloperstogroupsimilartasksintoclasses.
OneofthemajorbenefitsofDRYprogrammingisthat,ifapieceofinformationchangesinyourprogram,usuallyonlyonechangeisrequiredtoupdatethe
code.Oneofthebiggestnightmaresfordevelopersismaintainingcodewheredataisdeclaredoverandoveragain,meaninganychangestotheprogrambecomean
infinitelymorefrustratinggameofWhere sWaldo?astheyhuntforduplicateddataandfunctionality.
OOPisintimidatingtoalotofdevelopersbecauseitintroducesnewsyntaxand,ataglance,appearstobefarmorecomplexthansimpleprocedural,orinline,code.
However,uponcloserinspection,OOPisactuallyaverystraightforwardandultimatelysimplerapproachtoprogramming.
UnderstandingObjectsandClasses
BeforeyoucangettoodeepintothefinerpointsofOOP,abasicunderstandingofthedifferencesbetweenobjectsandclassesisnecessary.Thissectionwillgo
overthebuildingblocksofclasses,theirdifferentcapabilities,andsomeoftheiruses.
Recogni ingtheDifferencesBetweenObjectsandClasses
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
1/24
02/02/12
PhotosbyInstantJeffersonandJohnWardell
Developersstarttalkingaboutobjectsandclasses,andtheyappeartobeinterchangeableterms.Thisisnotthecase,however.
Rightoffthebat,there sconfusioninOOP:seasoneddevelopersstarttalkingaboutobjectsandclasses,andtheyappeartobeinterchangeableterms.Thisisnotthe
case,however,thoughthedifferencecanbetoughtowrapyourheadaroundatfirst.
Aclass,forexample,islikeabl ep in fo aho e.Itdefinestheshapeofthehouseonpaper,withrelationshipsbetweenthedifferentpartsofthehouseclearly
definedandplannedout,eventhoughthehousedoesn texist.
Anobject,then,islike heac alho ebuiltaccordingtothatblueprint.Thedatastoredintheobjectislikethewood,wires,andconcretethatcomposethehouse:
withoutbeingassembledaccordingtotheblueprint,it sjustapileofstuff.However,whenitallcomestogether,itbecomesanorganized,usefulhouse.
Cla e fo m he
c eofda aandac ion and e ha info ma ion ob ildobjec .Morethanoneobjectcanbebuiltfromthesameclassatthesame
time,eachoneindependentoftheothers.Continuingwithourconstructionanalogy,it ssimilartothewayanentiresubdivisioncanbebuiltfromthesameblueprint:
150differenthousesthatalllookthesamebuthavedifferent
familiesanddecorationsinside.
ingCla
Thesyntaxtocreateaclassisprettystraightforward:declareaclassusingtheclasskeyword,followedbythenameoftheclassandasetofcurlybraces({ ):
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
<?php
classMyClass
{
//Classpropertiesandmethodsgohere
}
?>
Aftercreatingtheclass,anewclasscanbeinstantiatedandstoredinavariableusingthenewkeyword:
viewplaincopytoclipboardprint?
1. $obj=newMyClass
Toseethecontentsoftheclass,usevar_dump():
viewplaincopytoclipboardprint?
1. var_dump($obj)
Tryoutthisprocessbyputtingalltheprecedingcodeinanewfilecalledtest.phpin[yourlocal]testingfolder:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
<?php
classMyClass
{
//Classpropertiesandmethodsgohere
}
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
2/24
02/02/12
6.
7.
8.
9.
10.
11.
12.
$obj=newMyClass
var_dump($obj)
?>
Loadthepageinyourbrowserathttp://localhost/test.phpandthefollowingshoulddisplay:
1. object(MyClass)#1(0){}
Initssimplestform,you vejustcompletedyourfirstOOPscript.
DefiningCla
P ope ie
Toadddatatoaclass,properties,orclassspecificvariables,areused.Theseworkexactlylikeregularvariables,exceptthey reboundtotheobjectandtherefore
canonlybeaccessedusingtheobject.
ToaddapropertytoM Class,addthefollowingcodetoyourscript:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
}
$obj=newMyClass
var_dump($obj)
?>
Thekeywordpublicdeterminesthevisibilityoftheproperty,whichyou lllearnaboutalittlelaterinthischapter.Next,thepropertyisnamedusingstandard
variablesyntax,andavalueisassigned(thoughclasspropertiesdonotneedaninitialvalue).
Toreadthispropertyandoutputittothebrowser,referencetheobjectfromwhichtoreadandthepropertytoberead:
viewplaincopytoclipboardprint?
1. echo$obj>prop1
Becausemultipleinstancesofaclasscanexist,iftheindividualobjectisnotreferenced,thescriptwouldbeunabletodeterminewhichobjecttoreadfrom.Theuse
ofthearrow(>)isanOOPconstructthataccessesthecontainedpropertiesandmethodsofagivenobject.
Modifythescriptintest.phptoreadoutthepropertyratherthandumpingthewholeclassbymodifyingthecodeasshown:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
}
$obj=newMyClass
echo$obj>prop1//Outputtheproperty
?>
Reloadingyourbrowsernowoutputsthefollowing:
viewplaincopytoclipboardprint?
1. I'maclassproperty!
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
3/24
02/02/12
1. I'maclassproperty!
DefiningCla
Me hod
Me hod areclassspecificfunctions.Individualactionsthatanobjectwillbeabletoperformaredefinedwithintheclassasmethods.
Forinstance,tocreatemethodsthatwouldsetandgetthevalueoftheclassproperty$prop1,addthefollowingtoyourcode:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
}
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
}
}
$obj=newMyClass
echo$obj>prop1
?>
No e OOPallowsobjectstoreferencethemselvesusing$this.Whenworkingwithinamethod,use$thisinthesamewayyouwouldusetheobjectname
outsidetheclass.
Tousethesemethods,callthemjustlikeregularfunctions,butfirst,referencetheobjecttheybelongto.ReadthepropertyfromM Class,changeitsvalue,andread
itoutagainbymakingthemodificationsbelow:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
}
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
}
}
$obj=newMyClass
echo$obj>getProperty()//Getthepropertyvalue
$obj>setProperty("I'manewpropertyvalue!")//Setanewone
echo$obj>getProperty()//Readitoutagaintoshowthechange
26. ?>
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
4/24
02/02/12
26. ?>
Reloadyourbrowser,andyou llseethefollowing:
viewplaincopytoclipboardprint?
1. I'maclassproperty!
2. I'manewpropertyvalue!
ThepowerofOOPbecomesapparentwhenusingmultipleinstancesofthe
sameclass.
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
}
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
}
}
//Createtwoobjects
$obj=newMyClass
$obj2=newMyClass
//Getthevalueof$prop1frombothobjects
echo$obj>getProperty()
echo$obj2>getProperty()
//Setnewvaluesforbothobjects
$obj>setProperty("I'manewpropertyvalue!")
$obj2>setProperty("Ibelongtothesecondinstance!")
//Outputbothobjects'$prop1value
echo$obj>getProperty()
echo$obj2>getProperty()
?>
Whenyouloadtheresultsinyourbrowser,theyreadasfollows:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
I'maclassproperty!
I'maclassproperty!
I'manewpropertyvalue!
Ibelongtothesecondinstance!
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
5/24
02/02/12
U ingCon
c o andDe
co
Whenanobjectisinstantiated,it softendesirabletosetafewthingsrightoffthebat.Tohandlethis,PHPprovidesthemagicmethod__construct(),whichis
calledautomaticallywheneveranewobjectis
created.
Forthepurposeofillustratingtheconceptofconstructors,addaconstructortoM Classthatwilloutputamessagewheneveranewinstanceoftheclassiscreated:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
}
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
}
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
}
}
//Createanewobject
$obj=newMyClass
//Getthevalueof$prop1
echo$obj>getProperty()
//Outputamessageattheendofthefile
echo"Endoffile.<br/>"
?>
No e__CLASS__returnsthenameoftheclassinwhichitiscalledthisiswhatisknownasamagicconstant.Thereareseveralavailablemagicconstants,which
youcanreadmoreaboutinthePHPmanual.
Reloadingthefileinyourbrowserwillproducethefollowingresult:
viewplaincopytoclipboardprint?
1. Theclass"MyClass"wasinitiated!
2. I'maclassproperty!
3. Endoffile.
Tocallafunctionwhentheobjectisdestroyed,the__destruct()magicmethodisavailable.Thisisusefulforclasscleanup(closingadatabaseconnection,for
instance).
Outputamessagewhentheobjectisdestroyedbydefiningthemagicmethod
__destruct()inM Class:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
6.
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
6/24
02/02/12
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
}
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
}
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
}
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
}
}
//Createanewobject
$obj=newMyClass
//Getthevalueof$prop1
echo$obj>getProperty()
//Outputamessageattheendofthefile
echo"Endoffile.<br/>"
?>
Withadestructordefined,reloadingthetestfileresultsinthefollowingoutput:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
Theclass"MyClass"wasinitiated!
I'maclassproperty!
Endoffile.
Theclass"MyClass"wasdestroyed.
Whentheendofafileisreached,PHPautomaticallyreleasesallresources.
Toexplicitlytriggerthedestructor,youcandestroytheobjectusingthe
function n e ():
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
}
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
}
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
20. }
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
7/24
02/02/12
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
//Createanewobject
$obj=newMyClass
//Getthevalueof$prop1
echo$obj>getProperty()
//Destroytheobject
unset($obj)
//Outputamessageattheendofthefile
echo"Endoffile.<br/>"
?>
Nowtheresultchangestothefollowingwhenloadedinyourbrowser:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
Theclass"MyClass"wasinitiated!
I'maclassproperty!
Theclass"MyClass"wasdestroyed.
Endoffile.
Con ertingtoaString
ToavoidanerrorifascriptattemptstooutputM Classasastring,anothermagicmethodisusedcalled__toString().
Without__toString(),a emp ing oo p heobjec a a
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
28. //Createanewobject
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
8/24
02/02/12
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
//Createanewobject
$obj=newMyClass
//Outputtheobjectasastring
echo$obj
//Destroytheobject
unset($obj)
//Outputamessageattheendofthefile
echo"Endoffile.<br/>"
?>
Thisresultsinthefollowing:
viewplaincopytoclipboardprint?
1. Theclass"MyClass"wasinitiated!
2.
3. Catchablefatalerror:ObjectofclassMyClasscouldnotbeconvertedtostringin/Applications/XAMPP/xamppfiles/htdocs/testing/test.phponline40
Toavoidthiserror,adda__ oS ring()method:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
publicfunction__toString()
{
echo"UsingthetoStringmethod:"
return$this>getProperty()
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
//Createanewobject
$obj=newMyClass
//Outputtheobjectasastring
echo$obj
//Destroytheobject
unset($obj)
//Outputamessageattheendofthefile
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
9/24
02/02/12
43.
44.
45.
46.
//Outputamessageattheendofthefile
echo"Endoffile.<br/>"
?>
Inthiscase,attemptingtoconverttheobjecttoastringresultsinacalltothegetPropert ()method.Loadthetestscriptinyourbrowsertoseetheresult:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
Tip
Theclass"MyClass"wasinitiated!
UsingthetoStringmethod:I'maclassproperty!
Theclass"MyClass"wasdestroyed.
Endoffile.
Inadditiontothemagicmethodsdiscussedinthissection,severalothersareavailable.Foracompletelistofmagicmethods,seethePHPmanualpage.
U ingCla
Inhe i ance
Cla e caninhe i heme hod andp ope ie ofano he cla usingthee tendskeyword.Forinstance,tocreateasecondclassthatextendsM Classand
addsamethod,youwouldaddthefollowingtoyourtestfile:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
}
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
}
publicfunction__toString()
{
echo"UsingthetoStringmethod:"
return$this>getProperty()
}
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
}
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
}
}
classMyOtherClassextendsMyClass
{
publicfunctionnewMethod()
{
echo"Fromanewmethodin".__CLASS__.".<br/>"
}
}
//Createanewobject
$newobj=newMyOtherClass
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
10/24
02/02/12
44.
45.
46.
47.
48.
49.
50.
51.
//Outputtheobjectasastring
echo$newobj>newMethod()
//Useamethodfromtheparentclass
echo$newobj>getProperty()
?>
Uponreloadingthetestfileinyourbrowser,thefollowingisoutput:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
Theclass"MyClass"wasinitiated!
FromanewmethodinMyOtherClass.
I'maclassproperty!
Theclass"MyClass"wasdestroyed.
O er ritingInheritedPropertiesandMethods
Tochangethebehaviorofanexistingpropertyormethodinthenewclass,youcansimplyoverwriteitbydeclaringitagaininthenewclass:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
publicfunction__toString()
{
echo"UsingthetoStringmethod:"
return$this>getProperty()
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
classMyOtherClassextendsMyClass
{
publicfunction__construct()
{
echo"Anewconstructorin".__CLASS__.".<br/>"
publicfunctionnewMethod()
{
43. echo"Fromanewmethodin".__CLASS__.".<br/>"
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
11/24
02/02/12
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
echo"Fromanewmethodin".__CLASS__.".<br/>"
//Createanewobject
$newobj=newMyOtherClass
//Outputtheobjectasastring
echo$newobj>newMethod()
//Useamethodfromtheparentclass
echo$newobj>getProperty()
?>
Thischangestheoutputinthebrowserto:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
AnewconstructorinMyOtherClass.
FromanewmethodinMyOtherClass.
I'maclassproperty!
Theclass"MyClass"wasdestroyed.
PreservingOriginalMethodFunctionalit WhileOverwritingMethods
Toaddnewfunctionalitytoaninheritedmethodwhilekeepingtheoriginalmethodintact,usetheparen keywordwiththe cope e ol ionope a o (::):
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
publicfunction__toString()
{
echo"UsingthetoStringmethod:"
return$this>getProperty()
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
publicfunctiongetProperty()
{
return$this>prop1."<br/>"
classMyOtherClassextendsMyClass
{
publicfunction__construct()
37. {
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
12/24
02/02/12
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
{
parent::__construct()//Calltheparentclass'sconstructor
echo"Anewconstructorin".__CLASS__.".<br/>"
}
publicfunctionnewMethod()
{
echo"Fromanewmethodin".__CLASS__.".<br/>"
}
}
//Createanewobject
$newobj=newMyOtherClass
//Outputtheobjectasastring
echo$newobj>newMethod()
//Useamethodfromtheparentclass
echo$newobj>getProperty()
?>
Thisoutputstheresultofboththeparentconstructorandthenewclass sconstructor:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
Theclass"MyClass"wasinitiated!
AnewconstructorinMyOtherClass.
FromanewmethodinMyOtherClass.
I'maclassproperty!
Theclass"MyClass"wasdestroyed.
AssigningtheVisibilit ofPropertiesandMethods
Foraddedcontroloverobjects,methodsandpropertiesareassignedvisibility.Thiscontrolshowandfromwherepropertiesandmethodscanbeaccessed.Thereare
threevisibilitykeywords:public,protected,andprivate.Inadditiontoitsvisibility,amethodorpropertycanbedeclaredasstatic,whichallowsthemtobe
accessedwithoutaninstantiationoftheclass.
Foraddedcontroloverobjects,methodsandpropertiesareassignedvisibility.
NoteVisibilityisanewfeatureasofPHP5.ForinformationonOOPcompatibilitywithPHP4,seethePHPmanualpage.
PublicPropertiesandMethods
Allthemethodsandpropertiesyou veusedsofarhavebeenpublic.Thismeansthattheycanbeaccessedanywhere,bothwithintheclassandexternally.
ProtectedPropertiesandMethods
Whenapropertyormethodisdeclaredprotected,itcanonl beaccessedwithintheclassitselforindescendantclasses(classesthatextendtheclass
containingtheprotectedmethod).
DeclarethegetPropert ()methodasprotectedinM Classandtrytoaccessitdirectlyfromoutsidetheclass:
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
13/24
02/02/12
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
publicfunction__toString()
{
echo"UsingthetoStringmethod:"
return$this>getProperty()
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
protectedfunctiongetProperty()
{
return$this>prop1."<br/>"
classMyOtherClassextendsMyClass
{
publicfunction__construct()
{
parent::__construct()
echo"Anewconstructorin".__CLASS__.".<br/>"
publicfunctionnewMethod()
{
echo"Fromanewmethodin".__CLASS__.".<br/>"
//Createanewobject
$newobj=newMyOtherClass
//Attempttocallaprotectedmethod
echo$newobj>getProperty()
?>
Uponattemptingtorunthisscript,thefollowingerrorshowsup:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
Theclass"MyClass"wasinitiated!
AnewconstructorinMyOtherClass.
Fatalerror:CalltoprotectedmethodMyClass::getProperty()fromcontext''in/Applications/XAMPP/xamppfiles/htdocs/testing/test.phponline55
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
14/24
02/02/12
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
publicfunction__toString()
{
echo"UsingthetoStringmethod:"
return$this>getProperty()
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
protectedfunctiongetProperty()
{
return$this>prop1."<br/>"
classMyOtherClassextendsMyClass
{
publicfunction__construct()
{
parent::__construct()
echo"Anewconstructorin".__CLASS__.".<br/>"
publicfunctionnewMethod()
{
echo"Fromanewmethodin".__CLASS__.".<br/>"
publicfunctioncallProtected()
{
return$this>getProperty()
//Createanewobject
$newobj=newMyOtherClass
//Calltheprotectedmethodfromwithinapublicmethod
echo$newobj>callProtected()
?>
Thisgeneratesthedesiredresult:
viewplaincopytoclipboardprint?
1. Theclass"MyClass"wasinitiated!
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
15/24
02/02/12
1.
2.
3.
4.
Theclass"MyClass"wasinitiated!
AnewconstructorinMyOtherClass.
I'maclassproperty!
Theclass"MyClass"wasdestroyed.
Pri atePropertiesandMethods
Apropertyormethoddeclaredprivateisaccessibleonl fromwithintheclassthatdefinesit.Thismeansthate enifane classe tendstheclassthatdefinesa
pri atepropert ,thatpropertyormethodwillnotbeavailableatallwithinthechildclass.
Todemonstratethis,declaregetPropert ()asprivateinM Class,andattempttocallcallProtected()from
M OtherClass:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
publicfunction__toString()
{
echo"UsingthetoStringmethod:"
return$this>getProperty()
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
privatefunctiongetProperty()
{
return$this>prop1."<br/>"
classMyOtherClassextendsMyClass
{
publicfunction__construct()
{
parent::__construct()
echo"Anewconstructorin".__CLASS__.".<br/>"
publicfunctionnewMethod()
{
echo"Fromanewmethodin".__CLASS__.".<br/>"
publicfunctioncallProtected()
{
return$this>getProperty()
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
16/24
02/02/12
52.
53.
54.
55.
56.
57.
58.
59.
//Createanewobject
$newobj=newMyOtherClass
//Useamethodfromtheparentclass
echo$newobj>callProtected()
?>
Reloadyourbrowser,andthefollowingerrorappears:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
Theclass"MyClass"wasinitiated!
AnewconstructorinMyOtherClass.
Fatalerror:CalltoprivatemethodMyClass::getProperty()fromcontext'MyOtherClass'in/Applications/XAMPP/xamppfiles/htdocs/testing/test.phponline49
<?php
classMyClass
{
public$prop1="I'maclassproperty!"
publicstatic$count=0
publicfunction__construct()
{
echo'Theclass"',__CLASS__,'"wasinitiated!<br/>'
}
publicfunction__destruct()
{
echo'Theclass"',__CLASS__,'"wasdestroyed.<br/>'
}
publicfunction__toString()
{
echo"UsingthetoStringmethod:"
return$this>getProperty()
}
publicfunctionsetProperty($newval)
{
$this>prop1=$newval
}
privatefunctiongetProperty()
{
return$this>prop1."<br/>"
}
publicstaticfunctionplusOne()
{
37. return"Thecountis".++self::$count.".<br/>"
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
17/24
02/02/12
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
return"Thecountis".++self::$count.".<br/>"
}
}
classMyOtherClassextendsMyClass
{
publicfunction__construct()
{
parent::__construct()
echo"Anewconstructorin".__CLASS__.".<br/>"
}
publicfunctionnewMethod()
{
echo"Fromanewmethodin".__CLASS__.".<br/>"
}
publicfunctioncallProtected()
{
return$this>getProperty()
}
}
do
{
//CallplusOnewithoutinstantiatingMyClass
echoMyClass::plusOne()
}while(MyClass::$count<10)
?>
No eWhenaccessingstaticproperties,thedollarsign
($)comesaf e he cope e ol ionope a o .
Whenyouloadthisscriptinyourbrowser,thefollowingisoutput:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
Thecountis1.
Thecountis2.
Thecountis3.
Thecountis4.
Thecountis5.
Thecountis6.
Thecountis7.
Thecountis8.
Thecountis9.
Thecountis10.
Commenting ithDocBlocks
TheDocBlockcommentingstyleisawidely
acceptedmethodofdocumentingclasses.
WhilenotanofficialpartofOOP,theDocBlockcommentingstyleisawidelyacceptedmethodofdocumentingclasses.Asidefromprovidingastandardfor
developerstousewhenwritingcode,ithasalsobeenadoptedbymanyofthemostpopularsoftwaredevelopmentkits(SDKs),suchasEclipseandNetBeans,and
willbeusedtogeneratecodehints.
ADocBlockisdefinedbyusingablockcommentthatstartswithanadditionalasterisk:
viewplaincopytoclipboardprint?
1. /**
2. *ThisisaverybasicDocBlock
3. */
TherealpowerofDocBlockscomeswiththeabilitytouse ag ,whichstartwithanatsymbol( )immediatelyfollowedbythetagnameandthevalueofthetag.
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
18/24
02/02/12
TherealpowerofDocBlockscomeswiththeabilitytousetags,whichstartwithanatsymbol(@)immediatelyfollowedbythetagnameandthevalueofthetag.
DocBlocktagsallowdeveloperstodefineauthorsofafile,thelicenseforaclass,thepropert ormethodinformation,andotherusefulinformation.
Themostcommontagsusedfollow:
@author:Theauthorofthecurrentelement(whichmightbeaclass,file,method,oranybitofcode)arelistedusingthistag.Multipleauthortagscanbeused
inthesameDocBlockifmorethanoneauthoriscredited.TheformatfortheauthornameisJohnDoe<john.doe@email.com>.
@cop right:Thissignifiesthecopyrightyearandnameofthecopyrightholderforthecurrentelement.Theformatis2010Cop rightHolder.
@license:Thislinkstothelicenseforthecurrentelement.Theformatforthelicenseinformationis
http:// .e ample.com/path/to/license.t tLicenseName.
@var:Thisholdsthetypeanddescriptionofavariableorclassproperty.Theformatist peelementdescription.
@param:Thistagshowsthetypeanddescriptionofafunctionormethodparameter.Theformatist pe$element_nameelementdescription.
@return:Thetypeanddescriptionofthereturnvalueofafunctionormethodareprovidedinthistag.Theformatist pereturnelementdescription.
AsampleclasscommentedwithDocBlocksmightlooklikethis:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
<?php
/**
*Asimpleclass
*
*Thisisthelongdescriptionforthisclass,
*whichcanspanasmanylinesasneeded.Itis
*notrequired,whereastheshortdescriptionis
*necessary.
*
*Itcanalsospanmultipleparagraphsifthe
*descriptionmeritsthatmuchverbiage.
*
*@authorJasonLengstorf<jason.lengstorf@ennuidesign.com>
*@copyright2010EnnuiDesign
*@licensehttp://www.php.net/license/3_01.txtPHPLicense3.01
*/
classSimpleClass
{
/**
*Apublicvariable
*
*@varstringstoresdatafortheclass
*/
public$foo
/**
*Sets$footoanewvalueuponclassinstantiation
*
*@paramstring$valavaluerequiredfortheclass
*@returnvoid
*/
publicfunction__construct($val)
{
$this>foo=$val
/**
*Multipliestwointegers
*
*Acceptsapairofintegersandreturnsthe
*productofthetwo.
*
*@paramint$batanumbertobemultiplied
*@paramint$bazanumbertobemultiplied
*@returninttheproductofthetwoparameters
*/
publicfunctionbar($bat,$baz)
{
50. return$bat*$baz
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
19/24
02/02/12
51.
52.
53.
54.
}
}
?>
Onceyouscantheprecedingclass,thebenefitsofDocBlockareapparent:everythingisclearlydefinedsothatthenextdevelopercanpickupthecodeandne e
ha e o onde ha a nippe ofcodedoe o ha i ho ldcon ain.
<?php
functionchangeJob($person,$newjob)
{
$person['job']=$newjob//Changetheperson'sjob
return$person
}
functionhappyBirthday($person)
{
++$person['age']//Add1totheperson'sage
return$person
}
$person1=array(
'name'=>'Tom',
'job'=>'ButtonPusher',
'age'=>34
)
$person2=array(
'name'=>'John',
'job'=>'LeverPuller',
'age'=>41
)
//Outputthestartingvaluesforthepeople
echo"<pre>Person1:",print_r($person1,TRUE),"</pre>"
echo"<pre>Person2:",print_r($person2,TRUE),"</pre>"
//Tomgotapromotionandhadabirthday
$person1=changeJob($person1,'BoxMover')
33. $person1=happyBirthday($person1)
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
20/24
02/02/12
34.
35.
36.
37.
38.
39.
40.
41.
42.
//Johnjusthadabirthday
$person2=happyBirthday($person2)
//Outputthenewvaluesforthepeople
echo"<pre>Person1:",print_r($person1,TRUE),"</pre>"
echo"<pre>Person2:",print_r($person2,TRUE),"</pre>"
?>
Whenexecuted,thecodeoutputsthefollowing:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
Person1:Array
(
[name]=>Tom
[job]=>ButtonPusher
[age]=>34
)
Person2:Array
(
[name]=>John
[job]=>LeverPuller
[age]=>41
)
Person1:Array
(
[name]=>Tom
[job]=>BoxMover
[age]=>35
)
Person2:Array
(
[name]=>John
[job]=>LeverPuller
[age]=>42
)
TheOOPApp oach
Here stheOOPapproachtoourexample:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
<?php
classPerson
{
private$_name
private$_job
private$_age
publicfunction__construct($name,$job,$age)
{
$this>_name=$name
$this>_job=$job
$this>_age=$age
}
15.
16. publicfunctionchangeJob($newjob)
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
21/24
02/02/12
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
publicfunctionchangeJob($newjob)
{
$this>_job=$newjob
}
publicfunctionhappyBirthday()
{
++$this>_age
}
}
//Createtwonewpeople
$person1=newPerson("Tom","ButtonPusher",34)
$person2=newPerson("John","LeverPuller",41)
//Outputtheirstartingpoint
echo"<pre>Person1:",print_r($person1,TRUE),"</pre>"
echo"<pre>Person2:",print_r($person2,TRUE),"</pre>"
//GiveTomapromotionandabirthday
$person1>changeJob("BoxMover")
$person1>happyBirthday()
//Johnjustgetsayearolder
$person2>happyBirthday()
//Outputtheendingvalues
echo"<pre>Person1:",print_r($person1,TRUE),"</pre>"
echo"<pre>Person2:",print_r($person2,TRUE),"</pre>"
?>
Thisoutputsthefollowinginthebrowser:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
Person1:PersonObject
(
[_name:private]=>Tom
[_job:private]=>ButtonPusher
[_age:private]=>34
)
Person2:PersonObject
(
[_name:private]=>John
[_job:private]=>LeverPuller
[_age:private]=>41
)
Person1:PersonObject
(
[_name:private]=>Tom
[_job:private]=>BoxMover
[_age:private]=>35
)
Person2:PersonObject
(
[_name:private]=>John
[_job:private]=>LeverPuller
[_age:private]=>42
)
There salittlebitmoresetupinvolvedtomaketheapproachobjectoriented,butaftertheclassisdefined,creatingandmodifyingpeopleisabreezeaperson s
informationdoesnotneedtobepassedorreturnedfrommethods,andonlyabsolutelyessentialinformationispassedtoeachmethod.
OOPwillsignificantlyreduceyourworkloadifimplementedproperly.
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
22/24
02/02/12
Onthesmallscale,thisdifferencemaynotseemlikemuch,butasyourapplicationsgrowinsize,OOPwillsignificantlyreduceyourworkloadifimplemented
properly.
TipNoteverythingneedstobeobjectoriented.Aquickfunctionthathandlessomethingsmallinoneplaceinsidetheapplicationdoesnotnecessarilyneedtobe
wrappedinaclass.Useyourbestjudgmentwhendecidingbetweenobjectorientedandproceduralapproaches.
Reason2:BetterOrgani ation
AnotherbenefitofOOPishowwellitlendsitselftobeingeasil packagedandcataloged.Eachclasscangenerallybekeptinitsownseparatefile,andifa
uniformnamingconventionisused,accessingtheclassesisextremelysimple.
Assumeyou vegotanapplicationwith150classesthatarecalleddynamicallythroughacontrollerfileattherootofyourapplicationfilesystem.All150classes
followthenamingconventioncla .cla name.inc.phpandresideintheincfolderofyourapplication.
ThecontrollercanimplementPHP s__a oload()functiontodynamicallypullinonlytheclassesitneedsastheyarecalled,ratherthanincludingall150inthe
controllerfilejustincaseorcomingupwithsomecleverwayofincludingthefilesinyourowncode:
viewplaincopytoclipboardprint?
1.
2.
3.
4.
5.
6.
<?php
function__autoload($class_name)
{
include_once'inc/class.'.$class_name.'.inc.php'
}
?>
Havingeachclassinaseparatefilealsomakescodemoreportableandeasiertoreuseinnewapplicationswithoutabunchofcopyingandpasting.
Reason3:EasierMaintenance
DuetothemorecompactnatureofOOPwhendonecorrectly,changesinthecodeareusuall mucheasiertospotandmakethaninalongspaghetticode
proceduralimplementation.
Ifaparticulararrayofinformationgainsanewattribute,aproceduralpieceofsoftwaremayrequire(inaworstcasescenario)thatthenewattributebeaddedtoeach
functionthatusesthearray.
AnOOPapplicationcouldpotentiallybeupdatedaseasilyaddingthenewpropertyandthenaddingthemethodsthatdealwithsaidproperty.
AlotofthebenefitscoveredinthissectionaretheproductofOOPincombinationwithDRYprogrammingpractices.Itisdefinitelypossibletocreateeasyto
maintainproceduralcodethatdoesn tcausenightmares,anditisequallypossibletocreateawfulobjectorientedcode.[ProPHPandjQuery]willattemptto
demonstrateacombinationofgoodcodinghabitsinconjunctionwithOOPtogeneratecleancodethat seasytoreadandmaintain.
Summar
Atthispoint,youshouldfeelcomfortablewiththeobjectorientedprogrammingstyle.LearningOOPisagreatwaytotakeyourprogrammingtothatnextlevel.
Whenimplementedproperly,OOPwillhelpyouproduceeasytoread,easytomaintain,portablecodethatwillsaveyou(andthedeveloperswhoworkwithyou)
hoursofextrawork.Areyoustuckonsomethingthatwasn tcoveredinthisarticle?AreyoualreadyusingOOPandhavesometipsforbeginners?Sharethemin
thecomments!
Author sNote ThistutorialwasanexcerptfromProPHPandjQuery(Apress,2010).
Like
Tags:objectorientedprogrammingoopphpPHP
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
23/24
02/02/12
Tags:objectorientedprogrammingoopphpPHP
B JasonLengstorf
JasonLengstorfisa25 earoldturbogeekhailingfromPortland,Oregon,whodesignsanddevelopswebsitesfor
CopterLabs.He'stheauthorofPHPforAbsoluteBeginners[2009Apress]andProPHPandjQuer [2010Apress],
aswellasarticlesforvariousonlinepublications.
net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
24/24