Tải bản đầy đủ (.pdf) (744 trang)

OReilly upgrading to PHP 5 jul 2004 ISBN 0596006365

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.41 MB, 744 trang )












TableofContents
Index
Reviews
Examples
ReaderReviews
Errata
Academic
WhyPHP5Rocks!

UpgradingtoPHP5
ByAdamTrachtenberg

Publisher :O'Reilly
PubDate :July2004
ISBN :0-596-00636-5
Pages :304


ThisnewbookistargetedtowardPHP
developerswhoarealreadyfamiliarwithPHP


4.UpgradingtoPHP5offersaconcise
appraisalofthedifferencesbetweenPHP4
andPHP5,adetailedlookatwhat'snewin
thislatestversion,andanexplanationofhow
thesechangesaffectyou.Thebookalso


coversmoreadvancedfeaturesandprovides
hands-onexperiencedthroughshort,sample
programsincludedthroughout.













TableofContents
Index
Reviews
Examples
ReaderReviews
Errata
Academic

WhyPHP5Rocks!

UpgradingtoPHP5
ByAdamTrachtenberg

Publisher :O'Reilly
PubDate :July2004
ISBN :0-596-00636-5
Pages :304



Copyright

Preface
WhoThisBookIsFor

WhoThisBookIsNotFor




What'sinThisBook




ConventionsUsedinThisBook





We'dLiketoHearfromYou

OtherResources
UsingCodeExamples
Acknowledgements


Chapter1.Introduction
Section1.1.WhyPHP5?





Section1.2.What'sNewinPHP5?

Section1.3.InstallingandConfiguringPHP5


Chapter2.Object-OrientedProgramming
Section2.1.WhatIsObject-OrientedProgramming?




Section2.2.MemoryManagement





Section2.4.ClassIntermediates

Section2.3.BasicClasses
Section2.5.Inheritance

Section2.6.MagicalMethods


Chapter3.MySQL
Section3.1.InstallingandConfiguring




Section3.2.ProceduralInterface



Section3.4.Object-OrientedInterface



Section3.5.BeforeandAfter:QueryingandRetrievingDatawithPrepared
Statements
Section3.6.BeforeandAfter:Subselects







Section3.3.BeforeandAfter:ConnectingtotheDatabaseServer

Section3.7.Transactions
Section3.8.BeforeandAfter:MakingMultipleQueries
Section3.9.SecuringConnectionswithSSL

Section3.10.PortingCodeandMigratingDatabases


Chapter4.SQLite
Section4.1.SQLiteBasics




Section4.2.AlternateSQLiteResultTypes




Section4.4.Indexes,ErrorHandling,andIn-MemoryTables

Section4.3.Object-OrientedInterface
Section4.5.Transactions

Section4.6.User-DefinedFunctions



Chapter5.XML
Section5.1.XMLExtensionsinPHP5




Section5.2.InstallingXMLandXSLTSupport




Section5.4.SimpleXML




Section5.6.BeforeandAfter:ReadingXMLintoaTree




Section5.8.ReadingXMLasEventswithSAX




Section5.10.BeforeandAfter:TransformingXMLwithXSLT

Section5.3.DOM

Section5.5.ConvertingBetweenSimpleXMLandDOMObjects
Section5.7.BeforeandAfter:SearchingXMLwithXPath
Section5.9.BeforeandAfter:CreatingNewXMLDocuments
Section5.11.ValidatingAgainstaSchema



Chapter6.IteratorsandSPL
Section6.1.BeforeandAfter:UsingIterators

Section6.2.ImplementingtheIteratorInterface




Section6.3.MySQLQueryIterator




Section6.5.SimpleXMLIterator




Section6.7.ImplementingtheRecursiveIteratorInterface





Section6.9.RedefiningClassIteration

Section6.4.ChainingIterators
Section6.6.BeforeandAfter:RecursiveDirectoryIteration
Section6.8.ArrayandObjectPropertyIteration
Section6.10.IteratorandSPLClassesandInterfaces


Chapter7.ErrorHandlingandDebugging
Section7.1.BeforeandAfter:HandlingErrors

Section7.2.TheBenefitsofExceptions




Section7.3.SystemExceptions




Section7.5.UserExceptions




Section7.7.ProcessingErrorswithaCustomHandler

Section7.4.TheExceptionClass
Section7.6.SettingaCustomExceptionHandler

Section7.8.DebuggingFunctions


Chapter8.Streams,Wrappers,andFilters
Section8.1.UsingtheStreamsAPI

Section8.2.WrapperOverview




Section8.3.WrapperDetails




Section8.5.FilteringStreams

Section8.4.CreatingWrappers
Section8.6.CreatingFilters


Chapter9.OtherExtensions
Section9.1.SOAP

Section9.2.Tidy

Section9.3.Reflection



Chapter10.PHP5inAction
Section10.1.DefiningYourDatabaseSchema




Section10.2.ThePersonClass




Section10.4.TheTemplateClass

Section10.3.TheaddressBookClass
Section10.5.AssemblingtheApplication

Section10.6.Wrap-UpandFutureDirections


AppendixA.IntroductiontoXML
SectionA.1.ComparingHTMLandXML





SectionA.2.Well-FormedXML




SectionA.3.Schemas




SectionA.4.Transformations
SectionA.5.XMLNamespaces

SectionA.6.XPath


AppendixB.AdditionalNewFeaturesandMinorChanges
SectionB.1.PassingOptionalParametersbyReference




SectionB.2.NewE_STRICTErrorSetting




SectionB.4.CLINowAllowsIndividualLineProcessing




SectionB.6.Oracle(oci8)ExtensionFunctionsRenamed





SectionB.8.UpdatedCOMExtension




SectionB.10.strrpos()UsestheEntireNeedle

SectionB.3.TreatingStringsasArraysCausesErrors
SectionB.5.CLIAlwaysProvidesargvandargc
SectionB.7.NewConfigurationDirectives
SectionB.9.Apache2CorrectlySetsPATH_TRANSLATED
SectionB.11.Windows95SupportDropped

SectionB.12.old_functionEliminated


AppendixC.InstallingPHP5AlongsidePHP4
SectionC.1.GeneralPHP5Configuration






SectionC.2.ModuleandCGI
SectionC.3.Windows
Colophon
Index



Copyright©2004O'ReillyMedia,Inc.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles().Formoreinformation,
contactourcorporate/institutionalsalesdepartment:(800)
998-9938or
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
UpgradingtoPHP5,theimageofGalapagostortoises,and
relatedtradedressaretrademarksofO'ReillyMedia,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.


Preface
PHPisapowerfulyeteasy-to-usetoolforcreatingdynamicweb
content.Theperfectlanguageforprojectsgreatandsmall,PHP
isusedbyYahoo!,millionsofpersonalhomepages,and

everythingin-between.Bestofall,PHPisopensourceandruns
onUnix,Windows,andMacOSX.
Thelatestversion,PHP5,containsrobustsupportforobjectorientedprogramming,anintegratedsuiteofXMLtools,anallnewMySQLextension,webserviceswithSOAPandREST,and
hundredsofotherimprovements.
Therearesomanyupdatesandnewfeatures,it'sdifficulttoget
ahandleonallthechanges.Documentationisscarce,
scattered,andrarelyin-depth.Thisbooksteadilyguidesyou
fromtheworldofPHP4toPHP5,coveringwhat'scompletely
new,what'sreceivedanoverhaul,andwhat'sjustslightly
differentenoughtoslipyouup.


WhoThisBookIsFor
ThisisthePHP5bookforPHP4programmers.Ifyou're
currentlyusingPHPandwanttolearnwhat'snewinPHP5,you
shouldbuythisbook.UnlikeotherPHP5books,Upgradingto
PHP5assumesyou'refamiliarwithPHP,soitdoesn'twaste
yourtimediscussinghowtoprocessformsandquery
databases.
Instead,UpgradingtoPHP5showsyouacompletecollectionof
detailedexamplescoveringallthelatestandgreatestfeatures
ofPHP5.Object-orientedprogramming?Check.MySQL?Check.
XML?Check.Ifit'spartofPHP5,it'spartofthisbook.
BesidesshowingoffPHP5,thisbookalsoeasesyourmigration
fromPHP4toPHP5.AsaveteranPHPprogrammer,youhave
pagesandpagesofexistingPHPcode.Notallofitwillwork
perfectlyunderPHP5.That'swhyUpgradingtoPHP5provides
youwithdetailedside-by-sidecomparisonsofPHP4andPHP5
solutions.Thisletsyouclearlyseetheexactchangesyouneed
tomaketoyourcurrentcode.

Inadditiontocoveringwhat'snewandhowit'snew,thisbook
tellsyouwhyit'snew.PHP5isn'tchangeforthesakeof
change.UpgradingtoPHP5explainsthelogicbehindthe
changesandshowshowyoucantakeadvantageofthemtothe
benefitofyourcode.
Finally,itprovidesanaddressbookprogram.Thisconcrete
examplecombinesthenewfeaturesofPHP5,demonstrating
theirusefulnessinthecontextofacompleteapplication.The
addressbookshowsyouexactlyhowPHP5makesitfasterand
easiertodevelopmorepowerfulandflexiblewebapplications.


WhoThisBookIsNotFor
ThisbookisnotforpeoplenewtoPHP.Ifyou'relookingtolearn
thelanguage,checkoutthesethreeexcellentalternatives:
1. LearningPHP5,byDavidSklar.Thisbookprovidesa
gentleintroductiontoPHPforwebdesignersand
othernontechnicalpeoplefamiliarwithHTMLandthe
Web,butnotwithprogramminganddatabases.
ProgrammingPHP,byRasmusLerdorfandKevinTatroe.CoauthoredbythecreatorofPHP,ProgrammingPHPisaimedat
anyonelookingtolearnPHP.Anexhaustivereference,thisbook
coversallaspectsofPHP,frombasicconceptstoadvanced
techniques.
WebDatabaseApplicationswithPHPandMySQL,byHugh
E.WilliamsandDavidLane.Ifyou'recomfortableprogramming
buthaveonlyjuststartedusingSQL,thisbookteachesyou
howtocreateanentiredatabase-backedwebsite.Web
DatabaseApplicationswithPHPandMySQLworksyouthrough
theentireprocess,includingdesign,coding,and
implementation.

ThesebooksareallpublishedbyO'ReillyMedia,Inc.


What'sinThisBook
Thisbookisdividedinto10chaptersand3appendixes.The
materialinthefirsthalfofthisbookcoversvitalcomponentsof
everydaywebprogramming:object-orientedprogramming,
MySQL,SQLite,andXML.It'shardtousePHP5withoutthem.
Specifically:
Chapter1,IntroductionexplainsthebackgroundofPHP5
anditsnewextensions.
Chapter2,Object-OrientedProgramming,coversobjectorientedprogrammingunderPHP5.
Chapter3,MySQL,examinesMySQLi,anewMySQL
databaseextension.ItalsodetailsSQLfeaturesofMySQL
4.0and4.1.
Chapter4,SQLite,talksaboutSQLite,anembedded
databaselibrary.
Chapter5,XML,teacheseverythingXML:DOM,XSLT,
SimpleXML,SAX,andXPath.
ThesecondhalfofthebookdiscussesmorespecializedPHP5
features.Iterators,exceptions,streams,SOAP,andother
extensionsareallextremelyusefulforsolvingspecifictasks.
ThemoreyouprograminPHP5,themoreyou'llfindyourself
integratingthesefeaturesintoyourcode.
Chapter6,IteratorsandSPL,showshowiteratorsandSPL
letyouloopthroughdirectories,databasequeries,andXML
documents.


Chapter7,ErrorHandlingandDebugging,helpsyouhandle

errorswithexceptionhandling.
Chapter8,Streams,Wrappers,andFilters,introduces
streams,wrappers,andfilters.
Chapter9,OtherExtensions,discussestheSOAPandTidy
extensionsandtheReflectionclasses.
Chapter10,PHP5inAction,putsthewholebooktogether
withasamplePHP5application.
Thethreeappendixescomplementtherestofthebook:
AppendixA,IntroductiontoXML,providesanintroduction
toXMLandNamespaces.
AppendixB,AdditionalNewFeaturesandMinorChanges,
documentsthechangesinPHP5notcoveredelsewherein
thebook.
AppendixC,InstallingPHP5AlongsidePHP4,detailshow
tointegratePHP5intoyourexistingwebserverandPHP4
setup.


OtherResources
Thesewebsitesandbooksareexcellentcompanionsto
UpgradingtoPHP5.

WebSites
ThereisatremendousamountofPHPreferencematerialonline.
WitheverythingfromtheannotatedPHPmanualtositeswith
periodicarticlesandtutorials,afastInternetconnectionrivalsa
largebookshelfinPHPdocumentaryusefulness.

TheAnnotatedPHPManual( />TheofficialPHPManualcontainsthousandsofpages
coveringallaspectsofPHP.It'saninvaluableresourcefor

lookingupfunctions.

PHPmailinglists( />DiscussPHPonthePHPmailinglists.Don'tbeshy,there'sa
listforeverytopic:programming,databases,andeven
Windows.Amailinglistarchivelivesat
/>
PHPPresentationarchive( />Agreatwaytokeepup-to-dateonallthelatestPHP
developments,thisarchivecontainsconference


presentationslides.

PEAR( />Don'treimplementthewheel,downloaditfromPEAR.
PEARthePHPExtensionandApplicationRepositorycontains
PHPclassesthatsimplifyformsprocessing,providea
databaseabstractionlayer,generateclassdocumentation,
andsolvehundredsofothertasks.

PECL( />PECLisPEAR'ssister.PECLthePHPExtensionCommunity
LibraryisacollectionofPHPextensionswritteninC.They're
justlikethebundledPHPextensions,exceptthey're
targetedataspecializedaudience.PECLcontainsmay
usefulextensions,includingaPHPcacheandoptimizer,
extensionstoletyoutalktoPerlandPythonfromPHP,and
anXMLpullparser.

PHPDevCenter( />AlargecollectionofPHParticlesandtutorialsfreely
availableontheweb.

PHPCommunity.org( />AgatheringplacewheremembersofthePHPcommunity

canhangoutandmeetotherPHPprogrammers.


Books
Thesebooksareallhelpfulproblem-solvingguidesand
references.Mostofthebooksinthelistareweb-specific,and
thetopsixbooksaremyfavoritePHPandMySQLtexts.
1. PHPCookbook,[1]byDavidSklarandAdam
Trachtenberg(O'Reilly,2003).
EssentialPHPTools:Modules,Extensions,andAccelerators,
byDavidSklar(Apress,2004).
AdvancedPHPProgramming,byGeorgeSchlossnagle(SAMS,
2004).
MySQLReferenceManual,byMichael"Monty"Widenius,
DavidAxmark,andMySQLAB(O'Reilly,2002);alsoavailableat
/>MySQLCookbook,byPaulDuBois(O'Reilly,2003).
HighPerformanceMySQL,byJeremyD.ZawodnyandDerek
J.Balling(O'Reilly,2004).
XMLinaNutshell,SecondEdition,byElliotteRustyHarold
andW.ScottMeans(O'Reilly,2002).
HTTPDeveloper'sHandbook,byChrisShiflett(SAMS,2003).
WebSecurity,Privacy&Commerce,SecondEdition,by
SimsonGarfinkelandGeneSpafford(O'Reilly,2001).
MasteringRegularExpressions,SecondEdition,byJeffreyE.
F.Friedl(O'Reilly,2002).


ConventionsUsedinThisBook
Thefollowingprogrammingandtypesettingconventionsare
usedinthisbook.


ProgrammingConventions
The<?phpand?>openingandclosingmarkersthatbeginand
endaPHPprogramaregenerallyomittedfromexamplesinthis
book,exceptinexampleswherethebodyofthecodeincludes
anopeningorclosingmarker.
TheexamplesinthisbookwerewrittentorununderPHP5on
bothUnixandWindows,exceptwherenotedinthetext.
Atthetimethisbookwenttopress,thelatestavailableversion
ofPHP5wasReleaseCandidate3(RC3).Also,MySQL4.1was
inbeta.Itispossiblethatsomechangesmayoccurbetween
RC3andthefinalrelease.Pleasechecktheonlineerrataat
forany
last-minuteupdates.

TypesettingConventions
Thefollowingtypographicalconventionsareusedinthisbook:

Italic
Indicatesnewterms,URLs,emailaddresses,filenames,file
extensions,pathnames,anddirectories.


Constantwidth
Indicatescommands,options,switches,variables,
attributes,keys,functions,types,classes,namespaces,
methods,modules,properties,parameters,values,objects,
events,eventhandlers,XMLtags,HTMLtags,macros,the
contentsoffiles,ortheoutputfromcommands.


ConstantWidthBold
Indicatestheoutputfromcodeexamples.

Constantwidthitalic
Showstextthatshouldbereplacedwithuser-supplied
values.

Thisiconsignifiesatip,suggestion,orgeneralnote.

Thisiconindicatesawarningorcaution.


UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"UpgradingtoPHP5,byAdamTrachtenberg.
Copyright2004O'ReillyMedia,Inc.,0-596-00636-5."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor

thepermissiongivenhere,feelfreetocontactusat



We'dLiketoHearfromYou
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,
examples,andanyadditionalinformation.Youcanaccessthis
pageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:
/>

Acknowledgements
Thisbookwouldnotexistwithouttheassistanceofmany,
many,manypeople.Theyhavemysinceregratitudeand
thanks.
MylargestdebtbelongstotheentirePHPcommunity.
UpgradingtoPHP5couldnotexistwithoutyourefforts.Iwant
tospecificallythankthesepeoplefortheirspecialassistance,

whethertheyknewtheyweregivingitornot:MarcusBoerger,
ZakGreant,AndiGutmans,SterlingHughes,DerickRethans,
RobRichards,GeorgRichter,GeorgeSchlossnagle,Christian
Stocker,andHansZaunere.
ThanksalsotothemembersofNYPHP(for
sharingproblems,ideas,andsolutions.I'mluckytohavethe
world'sbestPHPusergroupinmyhometown.
PortionsofChapter7wereinspiredinpartbyGunjanDoshi's
BestPracticesforExceptionHandlingarticleonONJava.com
( />Iofferhimmythanks.
BretMartinandRikFaithprovidedhosting.Becauseofthem,
thetechnicalreviewprocesswassmoothandeasy.
TwopeoplediligentlyreviewedUpgradingtoPHP5.Their
commentsandsuggestionsimmenselyimprovedallaspectsof
thebook.ChrisShiflettandDavidSklararethetwobest
technicalreviewersanauthorcouldhave.Iamproudtocall
themmyfriends.
IwanttothankalltheassociatesofO'ReillyMedia,Inc.fortheir
help.I'vemetmanyO'Reillyemployeesovertheyears,and
there'snotabozointhebunch.


Thesepeople,bothdirectlyandindirectly,contributedtothe
words,images,andpagesyouholdinyourhands:
Genevieved'Entremontpreparedthisbookforproduction
andrepairedmyprose.
chromaticpublishedmyPHParticlesonONLamp.com.
AcorneredAndyOramandBruceEpsteingraciously
providededitorialguidanceandsupportonelatenightat
FOOCamp.

RobRomanotransformedmycrayonsketchesintoworksof
art.
BetsyWaliszewskigotthewordoutearlyandoften.
However,twopeoplecontributedmoremessagestomyinbox
thantheotherscombined:TatianaDiazandNatTorkington.
IhavenoideahowTatianaDiazputupwithmyall-too-often
claimsof"Ohsure,Icanmakethatdeadline,"withoutreaching
throughtheInternetandstranglingme.Withouthergentle
prodding,UpgradingtoPHP5wouldn'tbeavailableuntilPHP6.
NatTorkingtonisagreateditor.HegavemeapushwhenIgot
stuckandhelpedmereframechapterswhentheybecame
misaligned.HeevenletsmemakePerl6jokesathisexpense.I
payhimthegreatestcomplimentIcan:thisbookwouldbefar
lesshelpfulwithouthim.
Thankstomyfamilyandfriendsfortheirsupportand
encouragement.
ExtraspecialthanksgotoElizabethHondl,mybeautiful
princessandtalkingfrog.


Chapter1.Introduction
PHP4isawildlypopularwebprogramminglanguage.Web
serversonover15,000,000domainssupportPHP.PHPisthe
mostpopularApachemodulebyalmosta2-to-1margin.Butif
PHP'ssogreat,whydoweneedPHP5?
Well,PHP4isn'tperfect.Whileitmakesdevelopingweb
applicationsquickandeasy,it'soccasionallyweighteddownby
itslegacybaggage.Thismakestacklingsomeproblems
unnecessarilydifficult.
Inparticular,PHP'sversionofobject-orientedprogramming

(OOP)lacksmanyfeatures,theMySQLextensiondoesn't
supportthenewMySQL4.1clientprotocol,andXMLsupportis
ahodgepodge.
Fortunately,PHP5improvesonPHP4inthreemajorareas:
Object-orientedprogramming
MySQL
XML
Theseitemshaveallbeencompletelyrewritten,turningthem
fromlimitationsintostarattractions.Whilethesechangesalone
warrantanewversionofPHP,PHP5alsoprovides:
SQLiteforanembeddeddatabase
Iterators


Errorhandlingusingexceptions
Streams
SOAP
Someofthesefeatures,suchasiteratorsandexceptions,are
availableonlyduetofundamentalchangesinPHP'score.
Others,suchasstreamsandSQLite,arePHP4.3featuresthat
havematuredintoprime-timeuseinPHP5.
Thisbookshowsyouhowtotakeadvantageofthesenew
featuresinyourapplications.Additionally,itplacesaspecial
emphasisonnotjusttellingyouwhat'snew,butshowingyou
howandwhyit'snew.
Wheneverpossible,there'sadirectcomparisonbetweenthe
PHP4methodofsolvingataskandthePHP5solution.ThePHP
5wayisfrequentlyshorter,moreelegant,andprovidesyou
withgreaterflexibility.Thebefore-and-afterexamples
demonstrateinclearcodewhat'sbetteraboutPHP5and

provideyouwithconcreteexamplestoeasethetransitionfrom
PHP4toPHP5.
ThischapterservesasadualintroductiontobothPHP5and
UpgradingtoPHP5.ItbeginswithabriefhistoryofPHPthat
providesthemotivationbehindPHP5.Thenextsection
providesashortdescriptionofallthemajornewfeaturesof
PHP5and,atthesametime,explainshowthebookis
organized.Thischapterendswithadiscussionofhowtoinstall
andconfigurePHP5.


1.1WhyPHP5?
TounderstandwhyPHP5cametoexist,it'snecessaryto
quicklyreviewtheevolutionofPHPasalanguage.
WhenRasmusLerdorfcreatedPHPbackin1995,itwasn'teven
calledPHPhisPersonalHomePage/FormsInterpreterlanguage
wasknownasPHP/FI.Atthetime,PHP/FI'smainfocuswas
solvingsmall-timewebtasks:guestbooks,hitcounters,and
basicformsprocessing.Itsmajorbenefitwasitssimplicity;
PHP/FImadeiteasytohandleallthemessytasksthrownata
webdeveloper.Additionally,it'sC-likesyntaxwasalready
understoodbymanyprogrammers.
Overthenexttwoyears,PHP/FIgraduallygrewinpopularity.
However,by1997,PHP/FIwasalreadyshowingitsage.Asthe
Internetgatheredsteam,programmersbegantocreatemore
complexapplications,suchase-commerceshoppingcarts.
PHP/FI'squirksandlimitationshindereddevelopment.Itwas
tooslowandwasmissingsomebasicfeatures,suchasforand
foreachloops.
TheseproblemscausedZeevSuraskiandAndiGutmans,of

Zendfame,tobeginworkonanewversionofPHP/FI.This
version,whichbecamePHP3,solvedmanydifficultiesfacedby
PHP/FIdeveloperswhileremainingtruetotheessentialnature
ofPHP/FI.
Inparticular,PHP3wasfasterandmoreefficientthanPHP/FI.
Thenewparseralsoprovidedtheopportunitytoironoutsome
languageoddities,makingPHPmoreconsistent.PHP3'sother
majoradvancewasaneasy-to-useextensionAPI.Developers
fromallovercontributedextensionstoPHP,effectivelyturning
PHPfromaprogramminglanguageintoanentireweb
developmentenvironment.


PHP3retainedPHP/FI'sproceduralsyntax,butitalso
introducedaverysimplisticobject-orientedsyntax.Originally
theresultofaweekendhack,developersflockedtoobjects,
muchtothesurpriseofZeevandAndi.Unfortunately,PHP3
wasill-equippedtoprovidealltheobject-orientedfeatures
developersdemanded.
AfewmonthsafterPHP3wentfinalinJuneof1998,work
startedonPHP4.Again,theproblemwasspeed.Thenew
extensioninfrastructureprovidedtheopportunitytocreate
largerandmorecomplexwebsitesthaneverimagined.Inthe
wordsofAlanGreenspan,"irrationalexuberance"wasathand.
WhilePHP4providedyetanotherburstofpower,itssecondary
objectivewasbackwardcompatibility.Therewasastrong
emphasisonnotbreakingPHP3scriptsunderPHP4.Asa
result,beefingupthecorelanguagewasnotamainfocusof
PHP4.PHP4wasreleasedinMay2000,almosttwoyearsafter
PHP3.

Alothashappenedoverthelastfouryears.Perlmaybethe
"ducttapeoftheInternet,"butPHPistherealgluethatholds
theWebtogether.However,PHPstillfaceschallenges.The
problemsofperformanceandflexibilityhavelongbeen
conquered,butnowPHPisunderattackfromthetwinfoesof
JavaandC#.
Overthepast10years,JavaandC#haveintroducedadvanced
object-orientedprogrammingconceptstowebdevelopment.Yet
inmanyways,despitealltheimprovements,PHP4.3isstillthe
sameprocedurallanguagethatRasmuswroteadecadeago.
PHP5finallygrantsdeveloperstheirwish,providingafullsetof
object-orientedfeatures.
Thesefeatures,whicharediscussedinChapter2,allow
developerstomoreeasilydeveloplarge-scaleapplications
withoutresortingtothecumbersomeworkaroundsnecessaryin
PHP4.Theyalsoletyouwritecleanercodethat'slesserror-


×