Documentos de Académico
Documentos de Profesional
Documentos de Cultura
by: MehdiAchour FriedhelmBetz AntonyDovgal NunoLopes HannesMagnusson GeorgRichter DamienSeguy JakubVrana Andseveralothers 20081017 EditedBy:PhilipOlson 19972008thePHPDocumentationGroup
PHPManual Preface
PHP,whichstandsfor"PHP:HypertextPreprocessor"isawidelyusedOpenSourcegeneralpurpose scriptinglanguagethatisespeciallysuitedforWebdevelopmentandcanbeembeddedintoHTML.Its syntaxdrawsuponC,Java,andPerl,andiseasytolearn.Themaingoalofthelanguageistoallowweb developerstowritedynamicallygeneratedwebpagesquickly,butyoucandomuchmorewithPHP.
AuthorsandContributors
Wehighlightthecurrentlymostactivepeopleonfrontpageofthemanual,buttherearemanymore contributorswhocurrentlyhelpinourworkorhaveprovidedagreatamountofhelptotheprojectinthe past.Therearealotofunnamedpeoplewhohelpoutwithusernotesonmanualpages,whichcontinuallyget includedinthereferences,theworkofwhomwearealsoverythankfulfor.Allofthelistsprovidedbelow areinalphabeticalorder.
AuthorsandEditors
Thefollowingcontributorsshouldberecognizedfortheimpacttheyhavemadeand/orcontinuetomakeby addingcontenttothemanual:BillAbt,JouniAhto,AlexanderAulbach,DanielBeckham,StigBakken,Jesus M.Castagnetto,RonChmara,SeanCoates,JohnCoggeshall,SimoneCortesi,MarkusFischer,WezFurlong, SaraGolemon,RuiHirokawa,BradHouse,PierreAlainJoye,EtienneKneuss,MoriyoshiKoizumi,Rasmus Lerdorf,AndrewLindeman,StanislavMalyshev,RafaelMartinez,RickMcGuire,YasuoOhgaki,Derick Rethans,RobRichards,SanderRoobol,EgonSchmid,ThomasSchoefbeck,SaschaSchumann,DanScott, MasahiroTakagi,MichaelWallner,LarsTorbenWilson,JimWinstead,JeroenvanWolffelaarandAndrei Zmievski. Thefollowingcontributorshavedonesignificantworkeditingthemanual:StigBakken,GaborHojtsy, HartmutHolzgraefeandEgonSchmid.
UserNoteMaintainers
Thecurrentlymostactivemaintainersare:FriedhelmBetz,EtienneKneuss,NunoLopes,Hannes Magnusson,FelipePenaandMaciekSokolewicz. Thesepeoplehavealsoputalotofeffortintomanagingusernotes:MehdiAchour,DanielBeckham, FriedhelmBetz,VictorBoivie,JesusM.Castagnetto,NicolasChaillan,RonChmara,SeanCoates,James Cox,VincentGevers,SaraGolemon,ZakGreant,SzabolcsHeilig,OliverHinckel,HartmutHolzgraefe, RasmusLerdorf,MatthewLi,AndrewLindeman,AidanLister,MaximMaletsky,BobbyMatthis,James Moore,PhilipOlson,SebastianPicklum,DerickRethans,SanderRoobol,DamienSeguy,JasonSheets,Tom Sommer,JaniTaskinen,YasuoOhgaki,JakubVrana,LarsTorbenWilson,JimWinstead,JaredWylesand JeroenvanWolffelaar.
Preface
GettingStarted Introduction
TableofContents
WhatcanPHPdo?
WhatisPHP?
PHP(recursiveacronymfor"PHP:HypertextPreprocessor")isawidelyusedopensourcegeneralpurpose scriptinglanguagethatisespeciallysuitedforwebdevelopmentandcanbeembeddedintoHTML. Nice,butwhatdoesthatmean?Anexample: Example#1Anintroductoryexample <!DOCTYPEHTMLPUBLIC"//W3C//DTDHTML4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Example</title> </head> <body> <?php echo"Hi,I'maPHPscript!"; ?> </body> </html> InsteadoflotsofcommandstooutputHTML(asseeninCorPerl),PHPpagescontainHTMLwith embeddedcodethatdoes"something"(inthiscase,output"Hi,I'maPHPscript!").ThePHPcodeis enclosedinspecialstartandendprocessinginstructions <?php and ?> thatallowyoutojumpintoandout of"PHPmode." WhatdistinguishesPHPfromsomethinglikeclientsideJavaScriptisthatthecodeisexecutedontheserver, generatingHTMLwhichisthensenttotheclient.Theclientwouldreceivetheresultsofrunningthatscript, butwouldnotknowwhattheunderlyingcodewas.Youcanevenconfigureyourwebservertoprocessall
WhatcanPHPdo?
Anything.PHPismainlyfocusedonserversidescripting,soyoucandoanythinganyotherCGIprogram cando,suchascollectformdata,generatedynamicpagecontent,orsendandreceivecookies.ButPHPcan domuchmore. TherearethreemainareaswherePHPscriptsareused.
Serversidescripting.ThisisthemosttraditionalandmaintargetfieldforPHP.Youneedthreethings tomakethiswork.ThePHPparser(CGIorservermodule),awebserverandawebbrowser.You needtorunthewebserver,withaconnectedPHPinstallation.YoucanaccessthePHPprogram outputwithawebbrowser,viewingthePHPpagethroughtheserver.Allthesecanrunonyourhome machineifyouarejustexperimentingwithPHPprogramming.Seetheinstallationinstructions sectionformoreinformation. Commandlinescripting.YoucanmakeaPHPscripttorunitwithoutanyserverorbrowser.You onlyneedthePHPparsertouseitthisway.Thistypeofusageisidealforscriptsregularlyexecuted usingcron(on*nixorLinux)orTaskScheduler(onWindows).Thesescriptscanalsobeusedfor simpletextprocessingtasks.SeethesectionaboutCommandlineusageofPHPformoreinformation. Writingdesktopapplications.PHPisprobablynottheverybestlanguagetocreateadesktop applicationwithagraphicaluserinterface,butifyouknowPHPverywell,andwouldliketouse someadvancedPHPfeaturesinyourclientsideapplicationsyoucanalsousePHPGTKtowritesuch programs.Youalsohavetheabilitytowritecrossplatformapplicationsthisway.PHPGTKisan extensiontoPHP,notavailableinthemaindistribution.IfyouareinterestedinPHPGTK,visitits ownwebsite.
PHPcanbeusedonallmajoroperatingsystems,includingLinux,manyUnixvariants(includingHPUX, SolarisandOpenBSD),MicrosoftWindows,MacOSX,RISCOS,andprobablyothers.PHPhasalso supportformostofthewebserverstoday.ThisincludesApache,MicrosoftInternetInformationServer, PersonalWebServer,NetscapeandiPlanetservers,OreillyWebsiteProserver,Caudium,Xitami, OmniHTTPd,andmanyothers.ForthemajorityoftheserversPHPhasamodule,fortheotherssupporting theCGIstandard,PHPcanworkasaCGIprocessor. SowithPHP,youhavethefreedomofchoosinganoperatingsystemandawebserver.Furthermore,youalso havethechoiceofusingproceduralprogrammingorobjectorientedprogramming,oramixtureofthem. AlthoughnoteverystandardOOPfeatureisimplementedinPHP4,manycodelibrariesandlarge applications(includingthePEARlibrary)arewrittenonlyusingOOPcode.PHP5fixestheOOPrelated weaknessesofPHP4,andintroducesacompleteobjectmodel.
AdabasD dBase Empress FilePro(readonly) Hyperwave IBMDB2 Informix Ingres InterBase FrontBase mSQL DirectMSSQL MySQL ODBC Oracle(OCI7andOCI8) Ovrimos PostgreSQL SQLite Solid Sybase Velocis Unixdbm
Wealsohaveadatabaseabstractionextension(namedPDO)allowingyoutotransparentlyuseanydatabase supportedbythatextension.AdditionallyPHPsupportsODBC,theOpenDatabaseConnectionstandard,so youcanconnecttoanyotherdatabasesupportingthisworldstandard. PHPalsohassupportfortalkingtootherservicesusingprotocolssuchasLDAP,IMAP,SNMP,NNTP, POP3,HTTP,COM(onWindows)andcountlessothers.Youcanalsoopenrawnetworksocketsandinteract usinganyotherprotocol.PHPhassupportfortheWDDXcomplexdataexchangebetweenvirtuallyallWeb programminglanguages.Talkingaboutinterconnection,PHPhassupportforinstantiationofJavaobjectsand usingthemtransparentlyasPHPobjects.YoucanalsouseourCORBAextensiontoaccessremoteobjects. PHPhasextremelyusefultextprocessingfeatures,fromthePOSIXExtendedorPerlregularexpressionsto parsingXMLdocuments.ForparsingandaccessingXMLdocuments,PHP4supportstheSAXandDOM standards,andyoucanalsousetheXSLTextensiontotransformXMLdocuments.PHP5standardizesall theXMLextensionsonthesolidbaseoflibxml2andextendsthefeaturesetaddingSimpleXMLand XMLReadersupport. Atlastbutnotleast,wehavemanyotherinterestingextensions,themnoGoSearchsearchenginefunctions, theIRCGatewayfunctions,manycompressionutilities(gzip,bz2,zip),calendarconversion,translation... AsyoucanseethispageisnotenoughtolistallthefeaturesandbenefitsPHPcanoffer.Readoninthe
sectionsaboutinstallingPHP,andseethefunctionreferencepartforexplanationoftheextensionsmentioned here.
Asimpletutorial
TableofContents
WhatdoIneed?
InthistutorialweassumethatyourserverhasactivatedsupportforPHPandthatallfilesendingin.phpare handledbyPHP.Onmostservers,thisisthedefaultextensionforPHPfiles,butaskyourserver administratortobesure.IfyourserversupportsPHP,thenyoudonotneedtodoanything.Justcreateyour .phpfiles,puttheminyourwebdirectoryandtheserverwillautomaticallyparsethemforyou.Thereisno needtocompileanythingnordoyouneedtoinstallanyextratools.ThinkofthesePHPenabledfilesas simpleHTMLfileswithawholenewfamilyofmagicaltagsthatletyoudoallsortsofthings.Mostweb hostsofferPHPsupport,butifyourhostdoesnot,considerreadingthePHPLinkssectionforresourceson findingPHPenabledwebhosts. Letussayyouwanttosavepreciousbandwidthanddeveloplocally.Inthiscase,youwillwanttoinstalla webserver,suchasApache,andofcoursePHP.Youwillmostlikelywanttoinstalladatabaseaswell, suchasMySQL. Youcaneitherinstalltheseindividuallyorchooseasimplerway.Ourmanualhasinstallationinstructionsfor PHP(assumingyoualreadyhavesomewebserversetup).IncaseyouhaveproblemswithinstallingPHP yourself,wewouldsuggestyouaskyourquestionsonourinstallationmailinglist.Ifyouchoosetogoon thesimplerroute,thenlocateapreconfiguredpackageforyouroperatingsystem,whichautomatically installsallofthesewithjustafewmouseclicks.ItiseasytosetupawebserverwithPHPsupportonany operatingsystem,includingMacOSX,LinuxandWindows.OnLinux,youmayfindrpmfindandPBone
helpfulforlocatingRPMs.YoumayalsowanttovisitaptgettofindpackagesforDebian.
YourfirstPHPenabledpage
Createafilenamedhello.phpandputitinyourwebserver'srootdirectory(DOCUMENT_ROOT)withthe followingcontent: Example#1OurfirstPHPscript:hello.php <html> <head> <title>PHPTest</title> </head> <body> <?phpecho'<p>HelloWorld</p>';?> </body> </html> Useyourbrowsertoaccessthefilewithyourwebserver'sURL,endingwiththe"/hello.php"filereference. WhendevelopinglocallythisURLwillbesomethinglikehttp://localhost/hello.phpor http://127.0.0.1/hello.phpbutthisdependsonthewebserver'sconfiguration.Ifeverythingisconfigured correctly,thisfilewillbeparsedbyPHPandthefollowingoutputwillbesenttoyourbrowser:
<html> <head> <title>PHPTest</title> </head> <body> <p>HelloWorld</p> </body> </html>
ThisprogramisextremelysimpleandyoureallydidnotneedtousePHPtocreateapagelikethis.Allit doesisdisplay:HelloWorldusingthePHPecho()statement.Notethatthefiledoesnotneedtobe executableorspecialinanyway.TheserverfindsoutthatthisfileneedstobeinterpretedbyPHPbecause youusedthe".php"extension,whichtheserverisconfiguredtopassontoPHP.Thinkofthisasanormal HTMLfilewhichhappenstohaveasetofspecialtagsavailabletoyouthatdoalotofinterestingthings. Ifyoutriedthisexampleanditdidnotoutputanything,itpromptedfordownload,oryouseethewholefile astext,chancesarethattheserveryouareondoesnothavePHPenabled,orisnotconfiguredproperly.Ask youradministratortoenableitforyouusingtheInstallationchapterofthemanual.Ifyouaredeveloping locally,alsoreadtheinstallationchaptertomakesureeverythingisconfiguredproperly.Makesurethatyou accessthefileviahttpwiththeserverprovidingyoutheoutput.Ifyoujustcallupthefilefromyourfile system,thenitwillnotbeparsedbyPHP.Iftheproblemspersistanyway,donothesitatetouseoneofthe manyPHPsupportoptions. ThepointoftheexampleistoshowthespecialPHPtagformat.Inthisexampleweused<?phptoindicate thestartofaPHPtag.ThenweputthePHPstatementandleftPHPmodebyaddingtheclosingtag,?>.You mayjumpinandoutofPHPmodeinanHTMLfilelikethisanywhereyouwant.Formoredetails,readthe manualsectiononthebasicPHPsyntax.
Note:ANoteonLineFeeds LinefeedshavelittlemeaninginHTML,howeveritisstillagoodideatomakeyourHTMLlook niceandcleanbyputtinglinefeedsin.Alinefeedthatfollowsimmediatelyafteraclosing?> willberemovedbyPHP.Thiscanbeextremelyusefulwhenyouareputtinginmanyblocksof PHPorincludefilescontainingPHPthataren'tsupposedtooutputanything.Atthesametimeit canbeabitconfusing.Youcanputaspaceaftertheclosing?>toforceaspaceandalinefeedto beoutput,oryoucanputanexplicitlinefeedinthelastecho/printfromwithinyourPHPblock. Note:ANoteonTextEditors TherearemanytexteditorsandIntegratedDevelopmentEnvironments(IDEs)thatyoucanuse tocreate,editandmanagePHPfiles.ApartiallistofthesetoolsismaintainedatPHPEditors List.Ifyouwishtorecommendaneditor,pleasevisittheabovepageandaskthepagemaintainer toaddtheeditortothelist.Havinganeditorwithsyntaxhighlightingcanbehelpful. Note:ANoteonWordProcessors WordprocessorssuchasStarOfficeWriter,MicrosoftWordandAbiwordarenotoptimalfor editingPHPfiles.Ifyouwishtouseoneforthistestscript,youmustensurethatyousavethefile asplaintextorPHPwillnotbeabletoreadandexecutethescript. Note:ANoteonWindowsNotepad IfyouarewritingyourPHPscriptsusingWindowsNotepad,youwillneedtoensurethatyour filesaresavedwiththe.phpextension.(Notepadaddsa.txtextensiontofilesautomatically unlessyoutakeoneofthefollowingstepstopreventit.)Whenyousavethefileandareprompted toprovideanameforthefile,placethefilenameinquotes(i.e."hello.php").Alternatively,you canclickonthe'TextDocuments'dropdownmenuinthe'Save'dialogboxandchangethe settingto"AllFiles".Youcanthenenteryourfilenamewithoutquotes. NowthatyouhavesuccessfullycreatedaworkingPHPscript,itistimetocreatethemostfamousPHP script!Makeacalltothephpinfo()functionandyouwillseealotofusefulinformationaboutyoursystem andsetupsuchasavailablepredefinedvariables,loadedPHPmodules,andconfigurationsettings.Takesome timeandreviewthisimportantinformation. Example#2GetsysteminformationfromPHP <?phpphpinfo();?>
SomethingUseful
Letusdosomethingmoreusefulnow.Wearegoingtocheckwhatsortofbrowserthevisitorisusing.For that,wechecktheuseragentstringthebrowsersendsaspartoftheHTTPrequest.Thisinformationisstored inavariable.VariablesalwaysstartwithadollarsigninPHP.Thevariableweareinterestedinrightnowis $_SERVER['HTTP_USER_AGENT']. Note:$_SERVERisaspecialreservedPHPvariablethatcontainsallwebserverinformation.Itis knownasasuperglobal.Seetherelatedmanualpageonsuperglobalsformoreinformation.
TherearemanytypesofvariablesavailableinPHP.IntheaboveexampleweprintedanArrayelement. Arrayscanbeveryuseful. $_SERVERisjustonevariablethatPHPautomaticallymakesavailabletoyou.Alistcanbeseeninthe ReservedVariablessectionofthemanualoryoucangetacompletelistofthembylookingattheoutputof thephpinfo()functionusedintheexampleintheprevioussection. YoucanputmultiplePHPstatementsinsideaPHPtagandcreatelittleblocksofcodethatdomorethanjust asingleecho.Forexample,ifyouwanttocheckforInternetExploreryoucandothis: Example#2Exampleusingcontrolstructuresandfunctions <?php if(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')!==FALSE){ echo'YouareusingInternetExplorer.<br/>'; } ?> Asampleoutputofthisscriptmaybe:
YouareusingInternetExplorer.<br/>
Hereweintroduceacoupleofnewconcepts.Wehaveanifstatement.Ifyouarefamiliarwiththebasic syntaxusedbytheClanguage,thisshouldlooklogicaltoyou.Otherwise,youshouldprobablypickupan introductoryPHPbookandreadthefirstcoupleofchapters,orreadtheLanguageReferencepartofthe manual. Thesecondconceptweintroducedwasthestrpos()functioncall.strpos()isafunctionbuiltintoPHPwhich searchesastringforanotherstring.Inthiscasewearelookingfor'MSIE'(socalledneedle)inside $_SERVER['HTTP_USER_AGENT'](socalledhaystack).Iftheneedleisfoundinsidethehaystack,the functionreturnsthepositionoftheneedlerelativetothestartofthehaystack.Otherwise,itreturnsFALSE.If itdoesnotreturnFALSE,theifexpressionevaluatestoTRUEandthecodewithinits{braces}isexecuted. Otherwise,thecodeisnotrun.Feelfreetocreatesimilarexamples,withif,else,andotherfunctionssuchas strtoupper()andstrlen().Eachrelatedmanualpagecontainsexamplestoo.Ifyouareunsurehowtouse functions,youwillwanttoreadboththemanualpageonhowtoreadafunctiondefinitionandthesection
aboutPHPfunctions. WecantakethisastepfurtherandshowhowyoucanjumpinandoutofPHPmodeeveninthemiddleofa PHPblock: Example#3MixingbothHTMLandPHPmodes <?php if(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')!==FALSE){ ?> <h3>strpos()musthavereturnednonfalse</h3> <p>YouareusingInternetExplorer</p> <?php }else{ ?> <h3>strpos()musthavereturnedfalse</h3> <p>YouarenotusingInternetExplorer</p> <?php } ?> Asampleoutputofthisscriptmaybe:
<h3>strpos()musthavereturnednonfalse</h3> <p>YouareusingInternetExplorer</p>
DealingwithForms
OneofthemostpowerfulfeaturesofPHPisthewayithandlesHTMLforms.Thebasicconceptthatis importanttounderstandisthatanyformelementwillautomaticallybeavailabletoyourPHPscripts.Please readthemanualsectiononVariablesfromexternalsourcesformoreinformationandexamplesonusing formswithPHP.HereisanexampleHTMLform: Example#1AsimpleHTMLform
<formaction="action.php"method="post"> <p>Yourname:<inputtype="text"name="name"/></p> <p>Yourage:<inputtype="text"name="age"/></p> <p><inputtype="submit"/></p> </form>
Thereisnothingspecialaboutthisform.ItisastraightHTMLformwithnospecialtagsofanykind.When theuserfillsinthisformandhitsthesubmitbutton,theaction.phppageiscalled.Inthisfileyouwouldwrite
Apartfromthehtmlspecialchars()and(int)parts,itshouldbeobviouswhatthisdoes.htmlspecialchars() makessureanycharactersthatarespecialinhtmlareproperlyencodedsopeoplecan'tinjectHTMLtagsor Javascriptintoyourpage.Fortheagefield,sinceweknowitisanumber,wecanjustconvertittoaninteger whichwillautomaticallygetridofanystraycharacters.YoucanalsohavePHPdothisforyouautomatically byusingthefilterextension.The$_POST['name']and$_POST['age']variablesareautomaticallysetforyou byPHP.Earlierweusedthe$_SERVERsuperglobal;abovewejustintroducedthe$_POSTsuperglobal whichcontainsallPOSTdata.NoticehowthemethodofourformisPOST.IfweusedthemethodGETthen ourforminformationwouldliveinthe$_GETsuperglobalinstead.Youmayalsousethe$_REQUEST superglobal,ifyoudonotcareaboutthesourceofyourrequestdata.Itcontainsthemergedinformationof GET,POSTandCOOKIEdata.Alsoseetheimport_request_variables()function. YoucanalsodealwithXFormsinputinPHP,althoughyouwillfindyourselfcomfortablewiththewell supportedHTMLformsforquitesometime.WhileworkingwithXFormsisnotforbeginners,youmightbe interestedinthem.WealsohaveashortintroductiontohandlingdatareceivedfromXFormsinourfeatures section.
UsingoldcodewithnewversionsofPHP
NowthatPHPhasgrowntobeapopularscriptinglanguage,therearealotofpublicrepositoriesand librariescontainingcodeyoucanreuse.ThePHPdevelopershavelargelytriedtopreservebackwards compatibility,soascriptwrittenforanolderversionwillrun(ideally)withoutchangesinanewerversionof PHP.Inpractice,somechangeswillusuallybeneeded. Twoofthemostimportantrecentchangesthataffectoldcodeare:
Thedeprecationoftheold$HTTP_*_VARSarrays(whichneedtobeindicatedasglobalwhenused insideafunctionormethod).ThefollowingsuperglobalarrayswereintroducedinPHP4.1.0.They are:$_GET,$_POST,$_COOKIE,$_SERVER,$_FILES,$_ENV,$_REQUEST,and$_SESSION. Theolder$HTTP_*_VARSarrays,suchas$HTTP_POST_VARS,alsoexist.AsofPHP5.0.0,thelong PHPpredefinedvariablearraysmaybedisabledwiththeregister_long_arraysdirective. Externalvariablesarenolongerregisteredintheglobalscopebydefault.Inotherwords,asofPHP 4.2.0thePHPdirectiveregister_globalsisoffbydefaultinphp.ini.Thepreferredmethodofaccessing thesevaluesisviathesuperglobalarraysmentionedabove.Olderscripts,books,andtutorialsmay relyonthisdirectivebeingon.Ifitwereon,forexample,onecoulduse$idfromtheURL http://www.example.com/foo.php?id=42.Whetheronoroff,$_GET['id']isavailable.
Formoredetailsonthesechanges,seethesectiononpredefinedvariablesandlinkstherein.
What'snext?
Withyournewknowledgeyoushouldbeabletounderstandmostofthemanualandalsothevariousexample scriptsavailableintheexamplearchives.Youcanalsofindotherexamplesonthephp.netwebsitesinthe linkssection:http://www.php.net/links.php. ToviewvariousslidepresentationsthatshowmoreofwhatPHPcando,seethePHPConferenceMaterial Site:http://talks.php.net/
InstallationandConfiguration GeneralInstallationConsiderations
Beforestartingtheinstallation,firstyouneedtoknowwhatdoyouwanttousePHPfor.Therearethree mainfieldsyoucanusePHP,asdescribedintheWhatcanPHPdo?section:
company.Thisway,youdon'tneedtosetupanythingonyourown,onlywriteyourPHPscripts,uploaditto theserveryourent,andseetheresultsinyourbrowser. IncaseofsettinguptheserverandPHPonyourown,youhavetwochoicesforthemethodofconnecting PHPtotheserver.FormanyserversPHPhasadirectmoduleinterface(alsocalledSAPI).Theseservers includeApache,MicrosoftInternetInformationServer,NetscapeandiPlanetservers.Manyotherservers havesupportforISAPI,theMicrosoftmoduleinterface(OmniHTTPdforexample).IfPHPhasnomodule supportforyourwebserver,youcanalwaysuseitasaCGIorFastCGIprocessor.Thismeansyousetup yourservertousetheCGIexecutableofPHPtoprocessallPHPfilerequestsontheserver. IfyouarealsointerestedtousePHPforcommandlinescripting(e.g.writescriptsautogeneratingsome imagesforyouoffline,orprocessingtextfilesdependingonsomeargumentsyoupasstothem),youalways needthecommandlineexecutable.Formoreinformation,readthesectionaboutwritingcommandlinePHP applications.Inthiscase,youneednoserverandnobrowser. WithPHPyoucanalsowritedesktopGUIapplicationsusingthePHPGTKextension.Thisisacompletely differentapproachthanwritingwebpages,asyoudonotoutputanyHTML,butmanagewindowsand objectswithinthem.FormoreinformationaboutPHPGTK,pleasevisitthesitededicatedtothis extension.PHPGTKisnotincludedintheofficialPHPdistribution. Fromnowon,thissectiondealswithsettingupPHPforwebserversonUnixandWindowswithserver moduleinterfacesandCGIexecutables.Youwillalsofindinformationonthecommandlineexecutablein thefollowingsections. PHPsourcecodeandbinarydistributionsforWindowscanbefoundathttp://www.php.net/downloads.php. Werecommendyoutochooseamirrornearesttoyoufordownloadingthedistributions.
InstallationonUnixsystems
TableofContents
Apache2.0onUnixsystems Lighttpd1.4onUnixsystems Caudium fhttpdrelatednotes Sun,iPlanetandNetscapeserversonSunSolaris CGIandcommandlinesetups HPUXspecificinstallationnotes OpenBSDinstallationnotes Solarisspecificinstallationtips DebianGNU/Linuxinstallationnotes
ThissectionwillguideyouthroughthegeneralconfigurationandinstallationofPHPonUnixsystems.Be suretoinvestigateanysectionsspecifictoyourplatformorwebserverbeforeyoubegintheprocess.
AsourmanualoutlinesintheGeneralInstallationConsiderationssection,wearemainlydealingwithweb centricsetupsofPHPinthissection,althoughwewillcoversettingupPHPforcommandlineusageaswell. ThereareseveralwaystoinstallPHPfortheUnixplatform,eitherwithacompileandconfigureprocess,or throughvariousprepackagedmethods.Thisdocumentationismainlyfocusedaroundtheprocessof compilingandconfiguringPHP.ManyUnixlikesystemshavesomesortofpackageinstallationsystem.This canassistinsettingupastandardconfiguration,butifyouneedtohaveadifferentsetoffeatures(suchasa secureserver,oradifferentdatabasedriver),youmayneedtobuildPHPand/oryourwebserver.Ifyouare unfamiliarwithbuildingandcompilingyourownsoftware,itisworthcheckingtoseewhethersomebodyhas alreadybuiltapackagedversionofPHPwiththefeaturesyouneed. Prerequisiteknowledgeandsoftwareforcompiling:
Apache1.3.xonUnixsystems
ThissectioncontainsnotesandhintsspecifictoApacheinstallsofPHPonUnixplatforms.Wealsohave instructionsandnotesforApache2onaseparatepage. Youcanselectargumentstoaddtotheconfigureonline10belowfromthelistofcoreconfigureoptions andfromextensionspecificoptionsdescribedattherespectiveplacesinthemanual.Theversionnumbers havebeenomittedhere,toensuretheinstructionsarenotincorrect.Youwillneedtoreplacethe'xxx'here withthecorrectvaluesfromyourfiles. Example#1InstallationInstructions(ApacheSharedModuleVersion)forPHP
1.gunzipapache_xxx.tar.gz 2.tarxvfapache_xxx.tar 3.gunzipphpxxx.tar.gz 4.tarxvfphpxxx.tar 5.cdapache_xxx 6../configureprefix=/wwwenablemodule=so 7.make 8.makeinstall 9.cd../phpxxx 10.Now,configureyourPHP.ThisiswhereyoucustomizeyourPHP withvariousoptions,likewhichextensionswillbeenabled.Doa
./configurehelpforalistofavailableoptions.Inourexample we'lldoasimpleconfigurewithApache1andMySQLsupport.Your pathtoapxsmaydifferfromourexample. ./configurewithmysqlwithapxs=/www/bin/apxs 11.make 12.makeinstall Ifyoudecidetochangeyourconfigureoptionsafterinstallation, youonlyneedtorepeatthelastthreesteps.Youonlyneedto restartapacheforthenewmoduletotakeeffect.Arecompileof Apacheisnotneeded. Notethatunlesstoldotherwise,'makeinstall'willalsoinstallPEAR, variousPHPtoolssuchasphpize,installthePHPCLI,andmore. 13.Setupyourphp.inifile: cpphp.inidist/usr/local/lib/php.ini Youmayedityour.inifiletosetPHPoptions.Ifyoupreferyour php.iniinanotherlocation,usewithconfigfilepath=/some/pathin step10. Ifyouinsteadchoosephp.inirecommended,becertaintoreadthelist ofchangeswithin,astheyaffecthowPHPbehaves. 14.Edityourhttpd.conftoloadthePHPmodule.Thepathontherighthand sideoftheLoadModulestatementmustpointtothepathofthePHP moduleonyoursystem.Themakeinstallfromabovemayhavealready addedthisforyou,butbesuretocheck. ForPHP4: LoadModulephp4_modulelibexec/libphp4.so ForPHP5: LoadModulephp5_modulelibexec/libphp5.so 15.AndintheAddModulesectionofhttpd.conf,somewhereunderthe ClearModuleList,addthis: ForPHP4: AddModulemod_php4.c ForPHP5: AddModulemod_php5.c 16.TellApachetoparsecertainextensionsasPHP.Forexample, let'shaveApacheparsethe.phpextensionasPHP.Youcould haveanyextension(s)parseasPHPbysimplyaddingmore,with eachseparatedbyaspace.We'lladd.phtmltodemonstrate. AddTypeapplication/xhttpdphp.php.phtml It'salsocommontosetupthe.phpsextensiontoshowhighlightedPHP source,thiscanbedonewith: AddTypeapplication/xhttpdphpsource.phps 17.UseyournormalprocedureforstartingtheApacheserver.(Youmust stopandrestarttheserver,notjustcausetheservertoreloadby usingaHUPorUSR1signal.)
Alternatively,toinstallPHPasastaticobject: Example#2InstallationInstructions(StaticModuleInstallationforApache)forPHP
1.gunzipcapache_1.3.x.tar.gz|tarxf 2.cdapache_1.3.x 3../configure 4.cd.. 5.gunzipcphp5.x.y.tar.gz|tarxf 6.cdphp5.x.y 7../configurewithmysqlwithapache=../apache_1.3.x 8.make 9.makeinstall 10.cd../apache_1.3.x 11../configureprefix=/wwwactivatemodule=src/modules/php5/libphp5.a (Theabovelineiscorrect!Yes,weknowlibphp5.adoesnotexistatthis stage.Itisn'tsupposedto.Itwillbecreated.) 12.make (youshouldnowhaveanhttpdbinarywhichyoucancopytoyourApachebindirif itisyourfirstinstallthenyouneedto"makeinstall"aswell) 13.cd../php5.x.y 14.cpphp.inidist/usr/local/lib/php.ini 15.Youcanedit/usr/local/lib/php.inifiletosetPHPoptions. Edityourhttpd.conforsrm.conffileandadd: AddTypeapplication/xhttpdphp.php
./configurewithapxswithpgsql
Thiswillcreatealibphp5.so(orlibphp4.soinPHP4)sharedlibrarythatisloadedintoApacheusinga LoadModulelineinApache'shttpd.conffile.ThePostgreSQLsupportisembeddedintothislibrary.
./configurewithapxswithpgsql=shared
Apache2.0onUnixsystems
ThissectioncontainsnotesandhintsspecifictoApache2.0installsofPHPonUnixsystems. Warning WedonotrecommendusingathreadedMPMinproductionwithApache2.UsethepreforkMPMinstead, oruseApache1.Forinformationonwhy,readtherelatedFAQentryonusingApache2withathreaded
TheseversionsofPHParecompatibletoApache2.0.40andlater. Apache2.0SAPIsupportstartedwithPHP4.2.0.PHP4.2.3workswithApache2.0.39,don'tuse anyotherversionofApachewithPHP4.2.3.However,therecommendedsetupistousePHP 4.3.0orlaterwiththemostrecentversionofApache2. AllmentionedversionsofPHPwillworkstillwithApache1.3.x. DownloadthemostrecentversionofApache2.0andafittingPHPversionfromtheabovementioned places.ThisquickguidecoversonlythebasicstogetstartedwithApache2.0andPHP.Formore informationreadtheApacheDocumentation.Theversionnumbershavebeenomittedhere,toensurethe instructionsarenotincorrect.Youwillneedtoreplacethe'NN'herewiththecorrectvaluesfromyourfiles. Example#1InstallationInstructions(Apache2SharedModuleVersion)
1.gzipdhttpd2_0_NN.tar.gz 2.tarxvfhttpd2_0_NN.tar 3.gunzipphpNN.tar.gz 4.tarxvfphpNN.tar 5.cdhttpd2_0_NN 6../configureenableso 7.make 8.makeinstall NowyouhaveApache2.0.NNavailableunder/usr/local/apache2, configuredwithloadablemodulesupportandthestandardMPMprefork. Totesttheinstallationuseyournormalprocedureforstarting theApacheserver,e.g.: /usr/local/apache2/bin/apachectlstart andstoptheservertogoonwiththeconfigurationforPHP: /usr/local/apache2/bin/apachectlstop. 9.cd../phpNN 10.Now,configureyourPHP.ThisiswhereyoucustomizeyourPHP withvariousoptions,likewhichextensionswillbeenabled.Doa ./configurehelpforalistofavailableoptions.Inourexample we'lldoasimpleconfigurewithApache2andMySQLsupport.Your pathtoapxsmaydiffer,infact,thebinarymayevenbenamedapxs2on yoursystem. ./configurewithapxs2=/usr/local/apache2/bin/apxswithmysql 11.make 12.makeinstall
Ifyoudecidetochangeyourconfigureoptionsafterinstallation, youonlyneedtorepeatthelastthreesteps.Youonlyneedto restartapacheforthenewmoduletotakeeffect.Arecompileof Apacheisnotneeded. Notethatunlesstoldotherwise,'makeinstall'willalsoinstallPEAR, variousPHPtoolssuchasphpize,installthePHPCLI,andmore. 13.Setupyourphp.ini cpphp.inidist/usr/local/lib/php.ini Youmayedityour.inifiletosetPHPoptions.Ifyoupreferhaving php.iniinanotherlocation,usewithconfigfilepath=/some/pathin step10. Ifyouinsteadchoosephp.inirecommended,becertaintoreadthelist ofchangeswithin,astheyaffecthowPHPbehaves. 14.Edityourhttpd.conftoloadthePHPmodule.Thepathontherighthand sideoftheLoadModulestatementmustpointtothepathofthePHP moduleonyoursystem.Themakeinstallfromabovemayhavealready addedthisforyou,butbesuretocheck. ForPHP4: LoadModulephp4_modulemodules/libphp4.so ForPHP5: LoadModulephp5_modulemodules/libphp5.so 15.TellApachetoparsecertainextensionsasPHP.Forexample,let'shave Apacheparse.phpfilesasPHP.InsteadofonlyusingtheApacheAddType directive,wewanttoavoidpotentiallydangerousuploadsandcreated filessuchasexploit.php.jpgfrombeingexecutedasPHP.Usingthis example,youcouldhaveanyextension(s)parseasPHPbysimplyadding them.We'lladd.phtmltodemonstrate. <FilesMatch\.php$> SetHandlerapplication/xhttpdphp </FilesMatch> Or,ifwewantedtoallow.php,.php2,.php3,.php4,.php5,.php6,and .phtmlfilestobeexecutedasPHP,butnothingelse,we'dusethis: <FilesMatch"\.ph(p[26]?|tml)$"> SetHandlerapplication/xhttpdphp </FilesMatch> Andtoallow.phpsfilestobeexecutedasPHPsourcefiles,addthis: <FilesMatch"\.phps$"> SetHandlerapplication/xhttpdphpsource </FilesMatch> 16.UseyournormalprocedureforstartingtheApacheserver,e.g.: /usr/local/apache2/bin/apachectlstart OR servicehttpdrestart
FollowingthestepsaboveyouwillhavearunningApache2webserverwithsupportforPHPasaSAPI module.OfcoursetherearemanymoreconfigurationoptionsavailableApacheandPHP.Formore informationtype./configurehelpinthecorrespondingsourcetree.Ifyouwishtobuildamultithreaded versionofApache2,youmustoverwritethestandardMPMModulepreforkeitherwithworkerorperchild. Todosoappendtoyourconfigurelineinstep6aboveeithertheoptionwithmpm=workerorwith mpm=perchild.Beforedoingso,pleasebewaretheconsequencesandhaveatleastafairunderstandofwhat theimplications.Formoreinformation,readtheApachedocumentationregardingMPMModules. Note:Ifyouwanttousecontentnegotiation,readtheApacheMultiViewsFAQ. Note:TobuildamultithreadedversionofApacheyoursystemmustsupportthreads.Thisalso impliestobuildPHPwithexperimentalZendThreadSafety(ZTS).Thereforenotallextensions mightbeavailable.TherecommendedsetupistobuildApachewiththestandardpreforkMPM Module.
Lighttpd1.4onUnixsystems
ThissectioncontainsnotesandhintsspecifictoLighttpd1.4installsofPHPonUnixsystems. PleaseusetheLighttpdtractolearnhowtoinstallLighttpdproperlybeforecontinuing. FastcgiisthepreferredSAPItoconnectPHPandLighttpd.Fastcgiisautomagicallyenabledinphpcgiin PHP5.3,butforolderversionsconfigurephpwithenablefastcgi.ToconfirmthatPHPhasfastcgienabled, phpvshouldcontainPHP5.2.5(cgifcgi)BeforePHP5.2.3,fastcgiwasenabledonthephpbinary(there wasnophpcgi).
LettingLighttpdspawnphpprocesses
ToconfigureLighttpdtoconnecttophpandspawnfastcgiprocesses,editlighttpd.conf.Socketsare preferredtoconnecttofastcgiprocessesonthelocalsystem. Example#1Partiallighttpd.conf
server.modules+=("mod_fastcgi") fastcgi.server=(".php"=> (( "socket"=>"/tmp/php.socket", "binpath"=>"/usr/local/bin/phpcgi", "binenvironment"=>( "PHP_FCGI_CHILDREN"=>"16", "PHP_FCGI_MAX_REQUESTS"=>"10000" ), "minprocs"=>1, "maxprocs"=>1, "idletimeout"=>20 )) )
Spawningwithspawnfcgi
Lighttpdprovidesaprogramcalledspawnfcgitoeasetheprocessofspawningfastcgiprocesseseasier.
Spawningphpcgi
Itispossibletospawnprocesseswithoutspawnfcgi,thoughabitofheavyliftingisrequired.Settingthe PHP_FCGI_CHILDRENenvironmentvarcontrolshowmanychildrenPHPwillspawntohandleincoming requests.SettingPHP_FCGI_MAX_REQUESTSwilldeterminehowlong(inrequests)eachchildwilllive. Here'sasimplebashscripttohelpspawnphpresponders. Example#2SpawningFastCGIResponders
#!/bin/sh #Locationofthephpcgibinary PHP=/usr/local/bin/phpcgi #PIDFilelocation PHP_PID=/tmp/php.pid #Bindingtoanaddress #FCGI_BIND_ADDRESS=10.0.1.1:10000 #Bindingtoadomainsocket FCGI_BIND_ADDRESS=/tmp/php.sock PHP_FCGI_CHILDREN=16 PHP_FCGI_MAX_REQUESTS=10000 enviPHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN\ PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS\ $PHPb$FCGI_BIND_ADDRESS& echo$!>"$PHP_PID"
ConnectingtoremoteFCGIinstances
Fastcgiinstancescanbespawnedonmultipleremotemachinesinordertoscaleapplications. Example#3Connectingtoremotephpfastcgiinstances
fastcgi.server=(".php"=> (("host"=>"10.0.0.2","port"=>1030), ("host"=>"10.0.0.3","port"=>1030))
Caudium
PHPcanbebuiltasaPikemodulefortheCaudiumwebserver.Followthesimpleinstructionsbelowto installPHPforCaudium. Example#1CaudiumInstallationInstructions
1.MakesureyouhaveCaudiuminstalledpriortoattemptingto installPHP4.ForPHP4toworkcorrectly,youwillneedPike 7.0.268ornewer.Forthesakeofthisexampleweassumethat Caudiumisinstalledin/opt/caudium/server/. 2.Changedirectorytophpx.y.z(wherex.y.zistheversionnumber). 3../configurewithcaudium=/opt/caudium/server 4.make 5.makeinstall 6.RestartCaudiumifit'scurrentlyrunning. 7.Logintothegraphicalconfigurationinterfaceandgotothe virtualserverwhereyouwanttoaddPHP4support. 8.ClickAddModuleandlocateandthenaddthePHP4ScriptSupportmodule. 9.Ifthedocumentationsaysthatthe'PHP4interpreterisn't available',makesurethatyourestartedtheserver.Ifyoudid check/opt/caudium/logs/debug/default.1foranyerrorsrelatedto <filename>PHP4.so</filename>.Alsomakesurethat <filename>caudium/server/lib/[pikeversion]/PHP4.so</filename> ispresent. 10.ConfigurethePHPScriptSupportmoduleifneeded.
fhttpdrelatednotes
TobuildPHPasanfhttpdmodule,answer"yes"to"Buildasanfhttpdmodule?"(thewithfhttpd=DIR optiontoconfigure)andspecifythefhttpdsourcebasedirectory.Thedefaultdirectoryis /usr/local/src/fhttpd.Ifyouarerunningfhttpd,buildingPHPasamodulewillgivebetterperformance,more controlandremoteexecutioncapability. Note:SupportforfhttpdisnolongeravailableasofPHP4.3.0.
Sun,iPlanetandNetscapeserversonSunSolaris
ThissectioncontainsnotesandhintsspecifictoSunJavaSystemWebServer,SunONEWebServer,iPlanet andNetscapeserverinstallsofPHPonSunSolaris. FromPHP4.3.3onyoucanusePHPscriptswiththeNSAPImoduletogeneratecustomdirectorylistings anderrorpages.AdditionalfunctionsforApachecompatibilityarealsoavailable.Forsupportincurrentweb serversreadthenoteaboutsubrequests. YoucanfindmoreinformationaboutsettingupPHPfortheNetscapeEnterpriseServer(NES)here:http:// benoit.noss.free.fr/php/installphp4.html TobuildPHPwithSunJSWS/SunONEWS/iPlanet/Netscapewebservers,entertheproperinstalldirectory forthewithnsapi=[DIR]option.Thedefaultdirectoryisusually/opt/netscape/suitespot/.Pleasealsoread/ phpxxxversion/sapi/nsapi/nsapireadme.txt. 1. Installthefollowingpackagesfromhttp://www.sunfreeware.com/oranotherdownloadsite: autoconf2.13 automake1.4 bison1_25sol26sparclocal flex2_5_4asol26sparclocal gcc2_95_2sol26sparclocal gzip1.2.4sol26sparclocal m41_4sol26sparclocal make3_76_1sol26sparclocal mysql3.23.24beta(ifyouwantmysqlsupport) perl5_005_03sol26sparclocal tar1.13(GNUtar) 2. Makesureyourpathincludestheproperdirectories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/binandmakeitavailabletoyoursystemexport PATH. 3. gunzipphpx.x.x.tar.gz(ifyouhavea.gzdist,otherwisegoto4). 4. tarxvfphpx.x.x.tar 5. ChangetoyourextractedPHPdirectory:cd../phpx.x.x 6. Forthefollowingstep,makesure/opt/netscape/suitespot/iswhereyournetscapeserverisinstalled. Otherwise,changetothecorrectpathandrun:
./configurewithmysql=/usr/local/mysql\ withnsapi=/opt/netscape/suitespot/\ enablelibgcc
ConfigurationInstructionsforSun/iPlanet/Netscape
theentireserver,addthefollowinglinetoyourdefaultobject:
<Objectname="default"> AuthTransfn=php4_auth_trans . . . </Object>
6. TousePHPAuthenticationonasingledirectory,addthefollowing:
<Objectppath="d:\path\to\authenticated\dir\*"> AuthTransfn=php4_auth_trans </Object>
CGIenvironmentandrecommendedmodificationsinphp.ini
ImportantwhenwritingPHPscriptsisthefactthatSunJSWS/SunONEWS/iPlanet/Netscapeisa multithreadedwebserver.Becauseofthatallrequestsarerunninginthesameprocessspace(thespaceofthe webserveritself)andthisspacehasonlyoneenvironment.IfyouwanttogetCGIvariableslike PATH_INFO,HTTP_HOSTetc.itisnotthecorrectwaytotrythisintheoldPHPwaywithgetenv()ora similarway(registerglobalstoenvironment,$_ENV).Youwouldonlygettheenvironmentoftherunning webserverwithoutanyvalidCGIvariables! Note:Whyarethere(invalid)CGIvariablesintheenvironment? Answer:Thisisbecauseyoustartedthewebserverprocessfromtheadminserverwhichrunsthe startupscriptofthewebserver,youwantedtostart,asaCGIscript(aCGIscriptinsideofthe adminserver!).ThisiswhytheenvironmentofthestartedwebserverhassomeCGIenvironment variablesinit.Youcantestthisbystartingthewebservernotfromtheadministrationserver.Use thecommandlineasrootuserandstartitmanuallyyouwillseetherearenoCGIlike environmentvariables. SimplychangeyourscriptstogetCGIvariablesinthecorrectwayforPHP4.xbyusingthesuperglobal $_SERVER.Ifyouhaveolderscriptswhichuse$HTTP_HOST,etc.,youshouldturnonregister_globalsin php.iniandchangethevariableordertoo(important:remove"E"fromit,becauseyoudonotneedthe environmenthere):
variables_order="GPCS" register_globals=On
Specialuseforerrorpagesorselfmadedirectorylistings(PHP>=4.3.3)
YoucanusePHPtogeneratetheerrorpagesfor"404NotFound"orsimilar.Addthefollowinglinetothe objectinobj.confforeveryerrorpageyouwanttooverwrite:
Errorfn="php4_execute"code=XXXscript="/path/to/script.php"[inikey=value inikey=value...]
ForbotherroranddirectorylistingpagestheoriginalURIandtranslatedURIareinthevariables $_SERVER['PATH_INFO']and$_SERVER['PATH_TRANSLATED'].
Noteaboutnsapi_virtual()andsubrequests(PHP>=4.3.3)
TheNSAPImodulenowsupportsthensapi_virtual()function(alias:virtual())tomakesubrequestsonthe webserverandinserttheresultinthewebpage.Thisfunctionusessomeundocumentedfeaturesfromthe NSAPIlibrary.OnUnixthemoduleautomaticallylooksfortheneededfunctionsandusesthemifavailable. Ifnot,nsapi_virtual()isdisabled. Note:Butbewarned:Supportfornsapi_virtual()isEXPERIMENTAL!!!
CGIandcommandlinesetups
ThedefaultistobuildPHPasaCGIprogram.Thiscreatesacommandlineinterpreter,whichcanbeused forCGIprocessing,orfornonwebrelatedPHPscripting.IfyouarerunningawebserverPHPhasmodule supportfor,youshouldgenerallygoforthatsolutionforperformancereasons.However,theCGIversion enablesuserstorundifferentPHPenabledpagesunderdifferentuserids. Warning AserverdeployedinCGImodeisopentoseveralpossiblevulnerabilities.PleasereadourCGIsecurity sectiontolearnhowtodefendyourselffromsuchattacks. AsofPHP4.3.0,someimportantadditionshavehappenedtoPHP.AnewSAPInamedCLIalsoexistsandit hasthesamenameastheCGIbinary.Whatisinstalledat{PREFIX}/bin/phpdependsonyourconfigureline andthisisdescribedindetailinthemanualsectionnamedUsingPHPfromthecommandline.Forfurther detailspleasereadthatsectionofthemanual.
Testing
IfyouhavebuiltPHPasaCGIprogram,youmaytestyourbuildbytypingmaketest.Itisalwaysagood ideatotestyourbuild.ThiswayyoumaycatchaproblemwithPHPonyourplatformearlyinsteadofhaving
tostrugglewithitlater.
UsingVariables
SomeserversuppliedenvironmentvariablesarenotdefinedinthecurrentCGI/1.1specification.Onlythe followingvariablesaredefinedthere:AUTH_TYPE,CONTENT_LENGTH,CONTENT_TYPE, GATEWAY_INTERFACE,PATH_INFO,PATH_TRANSLATED,QUERY_STRING,REMOTE_ADDR, REMOTE_HOST,REMOTE_IDENT,REMOTE_USER,REQUEST_METHOD,SCRIPT_NAME, SERVER_NAME,SERVER_PORT,SERVER_PROTOCOL,andSERVER_SOFTWARE.Everythingelse shouldbetreatedas'vendorextensions'.
HPUXspecificinstallationnotes
ThissectioncontainsnotesandhintsspecifictoinstallingPHPonHPUXsystems. TherearetwomainoptionsforinstallingPHPonHPUXsystems.Eithercompileit,orinstallapre compiledbinary. Officialprecompiledpackagesarelocatedhere:http://software.hp.com/ Untilthismanualsectionisrewritten,thedocumentationaboutcompilingPHP(andrelatedextensions)on HPUXsystemshasbeenremoved.Fornow,considerreadingthefollowingexternalresource:Building ApacheandPHPonHPUX11.11
OpenBSDinstallationnotes
ThissectioncontainsnotesandhintsspecifictoinstallingPHPonOpenBSD3.6.
UsingBinaryPackages
UsingbinarypackagestoinstallPHPonOpenBSDistherecommendedandsimplestmethod.Thecore packagehasbeenseparatedfromthevariousmodules,andeachcanbeinstalledandremovedindependently fromtheothers.ThefilesyouneedcanbefoundonyourOpenBSDCDorontheFTPsite. Themainpackageyouneedtoinstallisphp4core4.3.8.tgz,whichcontainsthebasicengine(plusgettext andiconv).Next,takealookatthemodulepackages,suchasphp4mysql4.3.8.tgzorphp4imap4.3.8.tgz. Youneedtousethephpxscommandtoactivateanddeactivatethesemodulesinyourphp.ini. Example#1OpenBSDPackageInstallExample
#pkg_addphp4core4.3.8.tgz #/usr/local/sbin/phpxss #cp/usr/local/share/doc/php4/php.inirecommended/var/www/conf/php.ini (addinmysql) #pkg_addphp4mysql4.3.8.tgz #/usr/local/sbin/phpxsamysql (addinimap) #pkg_addphp4imap4.3.8.tgz #/usr/local/sbin/phpxsaimap (removemysqlasatest) #pkg_deletephp4mysql4.3.8 #/usr/local/sbin/phpxsrmysql (installthePEARlibraries) #pkg_addphp4pear4.3.8.tgz
Readthepackages(7)manualpageformoreinformationaboutbinarypackagesonOpenBSD.
UsingPorts
YoucanalsocompileupPHPfromsourceusingtheportstree.However,thisisonlyrecommendedfor usersfamiliarwithOpenBSD.ThePHP4portissplitintotwosubdirectories:coreandextensions.The extensionsdirectorygeneratessubpackagesforallofthesupportedPHPmodules.Ifyoufindyoudonot wanttocreatesomeofthesemodules,usetheno_*FLAVOR.Forexample,toskipbuildingtheimap module,settheFLAVORtono_imap.
CommonProblems
ThedefaultinstallofApacherunsinsideachroot(2)jail,whichwillrestrictPHPscriptsto accessingfilesunder/var/www.Youwillthereforeneedtocreatea/var/www/tmpdirectoryforPHP sessionfilestobestored,oruseanalternativesessionbackend.Inaddition,databasesocketsneedto beplacedinsidethejailorlistenonthelocalhostinterface.Ifyouusenetworkfunctions,somefiles from/etcsuchas/etc/resolv.confand/etc/serviceswillneedtobemovedinto/var/www/etc.The OpenBSDPEARpackageautomaticallyinstallsintothecorrectchrootdirectories,sonospecial modificationisneededthere.MoreinformationontheOpenBSDApacheisavailableinthe OpenBSDFAQ. TheOpenBSD3.6packageforthegdextensionrequiresXFree86tobeinstalled.Ifyoudonotwish tousesomeofthefontfeaturesthatrequireX11,installthephp4gd4.3.8no_x11.tgzpackage instead.
OlderReleases
OlderreleasesofOpenBSDusedtheFLAVORSsystemtocompileupastaticallylinkedPHP.Sinceitis hardtogeneratebinarypackagesusingthismethod,itisnowdeprecated.Youcanstillusetheoldstable portstreesifyouwish,buttheyareunsupportedbytheOpenBSDteam.Ifyouhaveanycommentsabout this,thecurrentmaintainerfortheportisAnilMadhavapeddy(avsmatopenbsddotorg).
Solarisspecificinstallationtips
ThissectioncontainsnotesandhintsspecifictoinstallingPHPonSolarissystems.
Requiredsoftware
SolarisinstallsoftenlackCcompilersandtheirrelatedtools.ReadthisFAQforinformationonwhyusing GNUversionsforsomeofthesetoolsisnecessary.Therequiredsoftwareisasfollows:
gcc(recommended,otherCcompilersmaywork) make flex bison m4 autoconf automake perl gzip tar GNUsed
Inaddition,youwillneedtoinstall(andpossiblycompile)anyadditionalsoftwarespecifictoyour configuration,suchasOracleorMySQL.
UsingPackages
YoucansimplifytheSolarisinstallprocessbyusingpkgaddtoinstallmostofyourneededcomponents.
DebianGNU/Linuxinstallationnotes
ThissectioncontainsnotesandhintsspecifictoinstallingPHPonDebianGNU/Linux.
UsingAPT
WhileyoucanjustdownloadthePHPsourceandcompileityourself,usingDebian'spackagingsystemisthe simplestandcleanestmethodofinstallingPHP.IfyouarenotfamiliarwithbuildingsoftwareonLinux,this isthewaytogo. ThefirstdecisionyouneedtomakeiswhetheryouwanttoinstallApache1.3.xorApache2.x.The correspondingPHPpackagesarerespectivelynamedlibapachemodphp*andlibapache2modphp*.The stepsgivenbelowwilluseApache1.3.x.Pleasenotethat,asofthiswriting,thereisnoofficialDebian packagesofPHP5.ThenthestepsgivenbelowwillinstallPHP4.
PHPisavailableinDebianasCGIorCLIflavourtoo,namedrespectivelyphp4cgiandphp4cli.Ifyouneed them,you'lljusthavetoreproducethefollowingstepswiththegoodpackagenames.Anotherspecial packageyou'dwanttoinstallisphp4pear.ItcontainsaminimalPEARinstallationandthepear commandlineutility. IfyouneedmorerecentpackagesofPHPthantheDebian'sstableonesorifsomePHPmoduleslacksthe Debianofficialrepository,perhapsyoushouldtakealookathttp://www.aptget.org/.Oneoftheresults foundshouldbeDotdeb.ThisunofficialrepositoryismaintainedbyGuillaumePlessisandcontains DebianpackagesofthemostrecentversionsofPHP4andPHP5.Touseit,justaddthetofollowingtwo linestoyour/etc/apt/sources.listsandrunaptgetupdate: Example#1ThetwoDotdebrelatedlines
debhttp://packages.dotdeb.orgstableall debsrchttp://packages.dotdeb.orgstableall
Bettercontrolonconfiguration
Inthelastsection,PHPwasinstalledwithonlycoremodules.Thismaynotbewhatyouwantandyouwill soondiscoverthatyouneedmoreactivatedmodules,likeMySQL,cURL,GD,etc. WhenyoucompilePHPfromsourceyourself,youneedtoactivatemodulesviatheconfigurecommand. WithAPT,youjusthavetoinstalladditionalpackages.They'reallnamed'php4*'(or'php5*'ifyou installedPHP5fromathirdpartyrepository). Example#4GettingthelistofPHPadditionalpackages
#dpkgl'php4*'
IfyouchoosetoaddtheMySQL,cURLandGDsupporttoPHPthecommandwilllooksomethinglikethis: Example#5InstallPHPwithMySQL,cURLandGD
#aptgetinstallphp4mysqlphp4curlphp4gd
You'llonlyhavetostop/startApacheaspreviouslytoactivatethemodules.
CommonProblems
InstallationonMacOSX
TableofContents
UsingPackages
ThereareafewprepackagedandprecompiledversionsofPHPforMacOSX.Thiscanhelpinsettingupa standardconfiguration,butifyouneedtohaveadifferentsetoffeatures(suchasasecureserver,ora differentdatabasedriver),youmayneedtobuildPHPand/oryourwebserveryourself.Ifyouareunfamiliar withbuildingandcompilingyourownsoftware,it'sworthcheckingwhethersomebodyhasalreadybuilta packagedversionofPHPwiththefeaturesyouneed. ThefollowingresourcesoffereasytoinstallpackagesandprecompiledbinariesforPHPonMacOS:
UsingthebundledPHP
PHPhascomestandardwithMacssinceOSXversion10.0.0.EnablingPHPwiththedefaultwebserver requiresuncommentingafewlinesintheApacheconfigurationfilehttpd.confwhereastheCGIand/orCLI areenabledbydefault(easilyaccessibleviatheTerminalprogram). EnablingPHPusingtheinstructionsbelowismeantforquicklysettingupalocaldevelopmentenvironment. It'shighlyrecommendedtoalwaysupgradePHPtothenewestversion.Likemostlivesoftware,newer versionsarecreatedtofixbugsandaddfeaturesandPHPbeingisnodifferent.SeetheappropriateMACOS Xinstallationdocumentationforfurtherdetails.Thefollowinginstructionsaregearedtowardsabeginner withdetailsprovidedforgettingadefaultsetuptowork.Allusersareencouragedtocompile,orinstallanew packagedversion. Thestandardinstallationtypeisusingmod_php,andenablingthebundledmod_phponMacOSXforthe Apachewebserver(thedefaultwebserver,thatisaccessibleviaSystemPreferences)involvesthefollowing steps: 1. LocateandopentheApacheconfigurationfile.Bydefault,thelocationisasfollows: /etc/httpd/httpd.confUsingFinderorSpotlighttofindthisfilemayprovedifficultasbydefaultit's privateandownedbytherootuser. Note:OnewaytoopenthisisbyusingaUnixbasedtexteditorintheTerminal,for examplenano,andbecausethefileisownedbyrootwe'llusethesudocommandtoopen it(asroot)soforexampletypethefollowingintotheTerminalApplication(after,itwill promptforapassword):sudonano/etc/httpd/httpd.confNoteworthynanocommands:^w (search),^o(save),and^x(exit)where^representstheCtrlkey. 2. Withatexteditor,uncommentthelines(byremovingthe#)thatlooksimilartothefollowing(these twolinesareoftennottogether,locatethembothinthefile):
#LoadModulephp4_modulelibexec/httpd/libphp4.so #AddModulemod_php4.c
4. BesuretheDirectoryIndexloadsthedesireddefaultindexfileThisisalsosetinhttpd.conf.Typically index.phpandindex.htmlareused.Bydefaultindex.phpisenabledbecauseit'salsointhePHPcheck shownabove.Adjustaccordingly. 5. Setthephp.inilocationorusethedefaultAtypicaldefaultlocationonMacOSXis /usr/local/php/php.iniandacalltophpinfo()willrevealthisinformation.Ifaphp.iniisnotused,PHP willusealldefaultvalues.SeealsotherelatedFAQonfindingphp.ini. 6. LocateorsettheDocumentRootThisistherootdirectoryforallthewebfiles.Filesinthisdirectory areservedfromthewebserversothePHPfileswillparseasPHPbeforeoutputtingthemtothe browser.Atypicaldefaultpathis/Library/WebServer/Documentsbutthiscanbesettoanythingin httpd.conf.Alternatively,thedefaultDocumentRootforindividualusersis /Users/yourusername/Sites 7. Createaphpinfo()file Thephpinfo()functionwilldisplayinformationaboutPHP.Considercreatingafileinthe DocumentRootwiththefollowingPHPcode: <?phpphpinfo();?> 8. RestartApache,andloadthePHPfilecreatedaboveTorestart,eitherexecutesudoapachectl gracefulintheshellorstop/startthe"PersonalWebServer"optionintheOSXSystemPreferences. Bydefault,loadinglocalfilesinthebrowserwillhaveanURLlikeso:http://localhost/info.phpOr usingtheDocumentRootintheuserdirectoryisanotheroptionandwouldenduplookinglike:http:// localhost/~yourusername/info.php TheCLI(orCGIinolderversions)isappropriatelynamedphpandlikelyexistsas/usr/bin/php.Openupthe terminal,readthecommandlinesectionofthePHPmanual,andexecutephpvtocheckthePHPversionof thisPHPbinary.Acalltophpinfo()willalsorevealthisinformation.
CompilingforOSXServer
MacOSXServerinstall
1. GetthelatestdistributionsofApacheandPHP. 2. Untarthem,andruntheconfigureprogramonApachelikeso.
./configureexecprefix=/usr\ localstatedir=/var\ mandir=/usr/share/man\ libexecdir=/System/Library/Apache/Modules\ iconsdir=/System/Library/Apache/Icons\ includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers\ enableshared=max\ enablemodule=most\ target=apache
3. Ifyouwantthecompilertodosomeoptimization,youmayalsowanttoaddthisline:
setenvOPTIM=O2
4. Next,gotothePHP4sourcedirectoryandconfigureit.
./configureprefix=/usr\ sysconfdir=/etc\ localstatedir=/var\ mandir=/usr/share/man\ withxml\ withapache=/src/apache_1.3.12
php.inidist/usr/bin/php.ini.
InstallingforApacheonMacOSXClient
ThefollowinginstructionswillhelpyouinstallaPHPmodulefortheApachewebserverincludedinMacOS XusingtheMacOSGUI.ThisversionincludesMySQL,PostgreSQL,andiODBCdatabasesupport,cURL, GD,PDFLib,LDAP,andmore.TheseinstructionsaregraciouslyprovidedbyMarcLiyanage. Warning Besureyouknowwhatyou'redoingbeforeadvancingbeyondthispoint!Youcancauseirreparableharmto yourApacheinstallationotherwise. Note:TheseinstructionswillonlyworkwiththeoriginalApachewebserverasshippedby Apple.IfyourebuiltorupgradedyourApache,youwillhavetobuildyourownPHPmodule. Toinstall: 1. ForApache1.3,download:http://www2.entropy.ch/download/entropy php5.2.41.tar.gz 2. ForApache2,download:wgethttp://www2.entropy.ch/download/entropy php5.2.41apache2.tar.gz 3. Unpackthecompressed.tar.gzfile,butDONOTUSEStuffItExpander.Instead,useApple's BOMArchiveHelperorthecommandline. 4. Doubleclicktheinstallerpackageandfollowthedirectionsoftheinstallerapplication. That'sall!PHPshouldnowbeupandrunning.Youcantestitbydroppingafilenamedtest.phpintoyour Sitesfolderinyourhomedirectory.Intothatfile,writethisline:<?phpphpinfo()?>. Nowopenup127.0.0.1/~your_username/test.phpinyourwebbrowser.Youshouldseeastatustablewith informationaboutthePHPmodule.
InstallationonWindowssystems
TableofContents
WindowsInstaller(PHP5.1.0andearlier) ManualInstallationSteps
ActiveScript MicrosoftIIS/PWS Apache1.3.xonMicrosoftWindows Apache2.0.xonMicrosoftWindows Sun,iPlanetandNetscapeserversonMicrosoftWindows OmniHTTPdServer SambarServeronMicrosoftWindows XitamionMicrosoftWindows Buildingfromsource InstallationofextensionsonWindows
ThissectionappliestoWindows98/MeandWindowsNT/2000/XP/2003.PHPwillnotworkon16bit platformssuchasWindows3.1andsometimeswerefertothesupportedWindowsplatformsasWin32. Windows95isnolongersupportedasofPHP4.3.0. Note:Windows98/ME/NT4isnolongersupportedasofPHP5.3.0. Note:Windows95isnolongersupportedasofPHP4.3.0. TherearetwomainwaystoinstallPHPforWindows:eithermanuallyorbyusingtheinstaller. IfyouhaveMicrosoftVisualStudio,youcanalsobuildPHPfromtheoriginalsourcecode. OnceyouhavePHPinstalledonyourWindowssystem,youmayalsowanttoloadvariousextensionsfor addedfunctionality. Warning ThereareseveralallinoneinstallersovertheInternet,butnoneofthoseareendorsedbyPHP.net,aswe believethatusingoneoftheofficialwindowspackagesfromhttp://www.php.net/downloads.phpisthebest choicetohaveyoursystemsecureandoptimized.
WindowsInstaller(PHP5.2andlater)
TheWindowsPHPinstallerforlaterversionsofPHPisbuiltusingMSItechnologyusingtheWixToolkit( http://wix.sourceforge.net/).ItwillinstallandconfigurePHPandallthebuiltinandPECLextensions,as wellasconfiguremanyofthepopularwebserverssuchasIIS,Apache,andXitami. First,installyourselectedHTTP(web)serveronyoursystem,andmakesurethatitworks.Thenproceed withoneofthefollowinginstalltypes.
NormalInstall
RuntheMSIinstallerandfollowtheinstructionsprovidedbytheinstallationwizard.Youwillbeprompted toselecttheWebServeryouwishtoconfigurefirst,alongwithanyconfigurationdetailsneeded. Youwillthenbepromptedtoselectwhichfeaturesandextensionsyouwishtoinstallandenable.By selecting"Willbeinstalledonlocalharddrive"inthedropdownmenuforeachitemyoucantrigger
whethertoinstallthefeatureornot.Byselecting"Entirefeaturewillbeinstalledonlocalharddrive",you willbeabletoinstallallsubfeaturesoftheincludedfeature(forexamplebyselectingthisoptionsforthe feature"PDO"youwillinstallallPDODrivers). Warning Itisnotrecommendedtoinstallallextensionsbydefault,sincemanyotherthemrequiredependenciesfrom outsidePHPinordertofunctionproperly.Instead,usetheInstallationRepairModethatcanbetriggeredthru the'Add/RemovePrograms'controlpaneltoenableordisableextensionsandfeaturesafterinstallation. TheinstallerthensetsupPHPtobeusedinWindowsandthephp.inifile,andconfigurescertainwebservers tousePHP.TheinstallerwillcurrentlyconfigureIIS,Apache,Xitami,andSambarServer;ifyouareusinga differentwebserveryou'llneedtoconfigureitmanually.
SilentInstall
Theinstalleralsosupportsasilentmode,whichishelpfulforSystemsAdministratorstodeployPHPeasily. Tousesilentmode:
msiexec.exe/iphpVERSIONwin32install.msi/q
Youcancontroltheinstalldirectorybypassingitasaparametertotheinstall.Forexample,toinstallto e:\php:
msiexec.exe/iphpVERSIONwin32install.msi/qINSTALLDIR=e:\php
ThecurrentlistofFeaturestoinstallisasfollows:
MainExecutablephp.exeexecutable ScriptExecutablephpwin.exeexecutable ext_php_*thevariousextensions(forexample:ext_php_mysqlforMySQL) apache13Apache1.3module apache20Apache2.0module apache22Apache2,2module apacheCGIApacheCGIexecutable iis4ISAPIIISISAPImodule iis4CGIIISCGIexecutable NSAPISun/iPlanet/Netscapeservermodule XitamiXitamiCGIexecutable SambarSambarServerISAPImodule CGIphpcgi.exeexecutable PEARPEARinstaller ManualPHPManualinCHMFormat
FormoreinformationoninstallingMSIinstallersfromthecommandline,visithttp://msdn.microsoft.com/ enus/library/aa367988.aspx
UpgradingPHPwiththeInstall
Toupgrade,runtheinstallereithergraphicallyorfromthecommandlineasnormal.Theinstallerwillread yourcurrentinstalloptions,removeyouroldinstallation,andreinstallPHPwiththesameoptionsasbefore. ItisrecommendedthatyouusethismethodofkeepingPHPupdatedinsteadofmanuallyreplacingthefiles intheinstallationdirectory.
WindowsInstaller(PHP5.1.0andearlier)
TheWindowsPHPinstallerisavailablefromthedownloadspageathttp://www.php.net/downloads.php. ThisinstallstheCGIversionofPHPandforIIS,PWS,andXitami,itconfiguresthewebserveraswell.The installerdoesnotincludeanyextraexternalPHPextensions(php_*.dll)asyou'llonlyfindthoseinthe WindowsZipPackageandPECLdownloads. Note:WhiletheWindowsinstallerisaneasywaytomakePHPwork,itisrestrictedinmany aspectsas,forexample,theautomaticsetupofextensionsisnotsupported.Useoftheinstaller isn'tthepreferredmethodforinstallingPHP. First,installyourselectedHTTP(web)serveronyoursystem,andmakesurethatitworks. Runtheexecutableinstallerandfollowtheinstructionsprovidedbytheinstallationwizard.Twotypesof installationaresupportedstandard,whichprovidessensibledefaultsforallthesettingsitcan,and advanced,whichasksquestionsasitgoesalong. Theinstallationwizardgathersenoughinformationtosetupthephp.inifile,andconfigurecertainweb serverstousePHP.OneofthewebserversthePHPinstallerdoesnotconfigureforisApache,soyou'llneed toconfigureitmanually. Oncetheinstallationhascompleted,theinstallerwillinformyouifyouneedtorestartyoursystem,restart theserver,orjuststartusingPHP. Warning Beaware,thatthissetupofPHPisnotsecure.IfyouwouldliketohaveasecurePHPsetup,you'dbettergo onthemanualway,andseteveryoptioncarefully.Thisautomaticallyworkingsetupgivesyouaninstantly workingPHPinstallation,butitisnotmeanttobeusedononlineservers.
ManualInstallationSteps
ThisinstallguidewillhelpyoumanuallyinstallandconfigurePHPwithawebserveronMicrosoft Windows.Togetstartedyou'llneedtodownloadthezipbinarydistributionfromthedownloadspageat http://www.php.net/downloads.php. Althoughtherearemanyallinoneinstallationkits,andwealsodistributeaPHPinstallerforMicrosoft Windows,werecommendyoutakethetimetosetupPHPyourselfasthiswillprovideyouwithabetter understandingofthesystem,andenablesyoutoinstallPHPextensionseasilywhenneeded. Note:UpgradingfromapreviousPHPversion PreviouseditionsofthemanualsuggestmovingvariousiniandDLLfilesintoyourSYSTEM (i.e.C:\WINDOWS)folderandwhilethissimplifiestheinstallationprocedureitmakesupgrading difficult.Weadviseyouremoveallofthesefiles(likephp.iniandPHPrelatedDLLsfromthe WindowsSYSTEMfolder)beforemovingonwithanewPHPinstallation.Besuretobackup thesefilesasyoumightbreaktheentiresystem.Theoldphp.inimightbeusefulinsettingupthe newPHPaswell.Andasyou'llsoonlearn,thepreferredmethodforinstallingPHPistokeepall PHPrelatedfilesinonedirectoryandhavethisdirectoryavailabletoyoursystemsPATH. Note:MDACrequirements IfyouuseMicrosoftWindows98/NT4downloadthelatestversionoftheMicrosoftDataAccess Components(MDAC)foryourplatform.MDACisavailableat http://msdn.microsoft.com/data/.ThisrequirementexistsbecauseODBCisbuiltintothe distributedWindowsbinaries. Thefollowingstepsshouldbecompletedonallinstallationsbeforeanyserverspecificinstructionsare performed: Extractthedistributionfileintoadirectoryofyourchoice.IfyouareinstallingPHP4,extracttoC:\,asthe zipfileexpandstoafoldernamelikephp4.3.7Win32.IfyouareinstallingPHP5,extracttoC:\phpasthe zipfiledoesn'texpandasinPHP4.Youmaychooseadifferentlocationbutdonothavespacesinthepath (likeC:\ProgramFiles\PHP)assomewebserverswillcrashifyoudo. ThedirectorystructureextractedfromthezipisdifferentforPHPversions4and5andlooklikeasfollows: Example#1PHP4packagestructure
c:\php | +cli || ||php.exeCLIexecutableONLYforcommandlinescripting | +dllssupportDLLsrequiredbysomeextensions || ||expat.dll || ||fdftk.dll || ||... | +extensionsextensionDLLsforPHP ||
||php_bz2.dll || ||php_cpdf.dll || ||... | +mibssupportfilesforSNMP | +opensslsupportfilesforOpenssl | +pdfrelatedsupportfilesforPDF | +sapiSAPI(servermodulesupport)DLLs || ||php4apache.dll || ||php4apache2.dll || ||... | +PEARinitialcopyofPEAR | | |gopear.batPEARsetupscript | |... | |php.exeCGIexecutable | |... | |php.inidistdefaultphp.inisettings | |php.inirecommendedrecommendedphp.inisettings | |php4ts.dllcorePHPDLL | |...
Or: Example#2PHP5packagestructure
c:\php | +dev || ||php5ts.lib | +extextensionDLLsforPHP || ||php_bz2.dll || ||php_cpdf.dll || ||... | +extras || |+mibssupportfilesforSNMP || |+opensslsupportfilesforOpenssl ||
|+pdfrelatedsupportfilesforPDF || ||mime.magic | +pearinitialcopyofPEAR | | |gopear.batPEARsetupscript | |fdftk.dll | |... | |phpcgi.exeCGIexecutable | |phpwin.exeexecutesscriptswithoutanopenedcommandprompt | |php.exeCLIexecutableONLYforcommandlinescripting | |... | |php.inidistdefaultphp.inisettings | |php.inirecommendedrecommendedphp.inisettings | |php5activescript.dll | |php5apache.dll | |php5apache2.dll | |... | |php5ts.dllcorePHPDLL | |...
sapi/php4nsapi.dll(php5nsapi.dll)Sun/iPlanet/Netscapeservermodule. sapi/php4pi3web.dll(noequivalentinPHP5)Pi3Webservermodule.
Tomakephp4ts.dll/php5ts.dllavailableyouhavethreeoptions:copythefiletotheWindowssystem directory,copythefiletothewebserver'sdirectory,oraddyourPHPdirectory,C:\phptothePATH.For bettermaintenance,weadviseyoutofollowthelastoption,addC:\phptothePATH,becauseitwillbe simplertoupgradePHPinthefuture.ReadmoreabouthowtoaddyourPHPdirectorytoPATHinthe correspondingFAQentry(andthendon'tforgettorestartthecomputerlogoffisn'tenough). ThenextstepistosetupavalidconfigurationfileforPHP,php.ini.Therearetwoinifilesdistributedinthe zipfile,php.inidistandphp.inirecommended.Weadviseyoutousephp.inirecommended,becausewe optimizedthedefaultsettingsinthisfileforperformance,andsecurity.Readthiswelldocumentedfile carefullybecauseithaschangesfromphp.inidistthatwilldrasticallyaffectyoursetup.Someexamplesare display_errorsbeingoffandmagic_quotes_gpcbeingoff.Inadditiontoreadingthese,studytheinisettings andseteveryelementmanuallyyourself.Ifyouwouldliketoachievethebestsecurity,thenthisistheway foryou,althoughPHPworksfinewiththesedefaultinifiles.Copyyourchoseninifiletoadirectorythat PHPisabletofindandrenameittophp.ini.PHPsearchesforphp.iniinthelocationsdescribedinRuntime Configurationsection. IfyouarerunningApache2,thesimpleroptionistousethePHPIniDirdirective(readtheinstallationon Apache2page),otherwiseyourbestoptionistosetthePHPRCenvironmentvariable.Thisprocessis explainedinthefollowingFAQentry. Note:Ifyou'reusingNTFSonWindowsNT,2000,XPor2003,makesurethattheuserrunning thewebserverhasreadpermissionstoyourphp.ini(e.g.makeitreadablebyEveryone). Thefollowingstepsareoptional:
Edityournewphp.inifile.IfyouplantouseOmniHTTPd,donotfollowthenextstep.Setthe doc_roottopointtoyourwebserversdocument_root.Forexample:
doc_root=c:\inetpub\wwwroot//forIIS/PWS
doc_root=c:\apache\htdocs//forApache
PHPisnowsetuponyoursystem.Thenextstepistochooseawebserver,andenableittorunPHP.Choose awebserverfromthetableofcontents.
ActiveScript
ThissectioncontainsnotesspecifictotheActiveScriptinstallation. ActiveScriptisaWindowsonlySAPIthatenablesyoutousePHPscriptinanyActiveScriptcomplianthost, likeWindowsScriptHost,ASP/ASP.NET,WindowsScriptComponentsorMicrosoftScriptletcontrol. AsofPHP5.0.1,ActiveScripthasbeenmovedtothePECLrepository.TheDLLforthisPECLextension maybedownloadedfromeitherthePHPDownloadspageorfromhttp://pecl4win.php.net/ Note:Youshouldreadthemanualinstallationstepsfirst! AfterinstallingPHP,youshoulddownloadtheActiveScriptDLL(php5activescript.dll)andplaceitinthe mainPHPfolder(e.g.C:\php). Afterhavingallthefilesneeded,youmustregistertheDLLonyoursystem.Toachievethis,opena CommandPromptwindow(locatedintheStartMenu).ThengotoyourPHPdirectorybytypingsomething likecdC:\php.ToregistertheDLLjusttyperegsvr32php5activescript.dll. TotestifActiveScriptisworking,createanewfile,namedtest.wsf(theextensionisveryimportant)and type:
<jobid="test"> <scriptlanguage="PHPScript"> $WScript>Echo("HelloWorld!"); </script> </job>
MicrosoftIIS/PWS
ThissectioncontainsnotesandhintsspecifictoIIS(MicrosoftInternetInformationServer). Warning AserverdeployedinCGImodeisopentoseveralpossiblevulnerabilities.PleasereadourCGIsecurity sectiontolearnhowtodefendyourselffromsuchattacks.
GeneralconsiderationsforallinstallationsofPHPwithIISorPWS
First,readtheManualInstallationInstructions.Donotskipthisstepasitprovidescrucialinformation forinstallingPHPonWindows. CGIusersmustsetthecgi.force_redirectPHPdirectiveto0insidephp.ini.Readthefaqon cgi.force_redirectforimportantdetails.Also,CGIusersmaywanttosetthecgi.redirect_status_env directive.Whenusingdirectives,besurethesedirectivesaren'tcommentedoutinsidephp.ini. ThePHP4CGIisnamedphp.exewhileinPHP5it'sphpcgi.exe.InPHP5,php.exeistheCLI,and nottheCGI. ModifytheWindowsPATHenvironmentvariabletoincludethePHPdirectory.ThiswaythePHP DLLfilesandPHPexecutablescanallremaininthePHPdirectorywithoutclutteringupthe Windowssystemdirectory.Formoredetails,seetheFAQonSettingthePATH. TheIISuser(usuallyIUSR_MACHINENAME)needspermissiontoreadvariousfilesand directories,suchasphp.ini,docroot,andthesessiontmpdirectory. Besuretheextension_diranddoc_rootPHPdirectivesareappropriatelysetinphp.ini.These directivesdependonthesystemthatPHPisbeinginstalledon.InPHP4,theextension_diris extensionswhilewithPHP5it'sext.So,anexamplePHP5extensions_dirvalueis"c:\php\ext"and anexampleIISdoc_rootvalueis"c:\Inetpub\wwwroot". PHPextensionDLLfiles,suchasphp_mysql.dllandphp_curl.dll,arefoundinthezippackageofthe PHPdownload(notthePHPinstaller).InPHP5,manyextensionsarepartofPECLandcanbe downloadedinthe"CollectionofPECLmodules"package.Filessuchasphp_zip.dlland php_ssh2.dll.DownloadPHPfileshere. Whendefiningtheexecutable,the'checkthatfileexists'boxmayalsobechecked.Forasmall performancepenalty,theIIS(orPWS)willcheckthatthescriptfileexistsandsortoutauthentication beforefiringupPHP.Thismeansthatthewebserverwillprovidesensible404styleerrormessages insteadofCGIerrorscomplainingthatPHPdidnotoutputanydata. ThePHPexecutableisdistributedasa32bitapplication.Ifyouarerunninga64bitversionof Windowsyouwilleitherneedtorebuildthebinaryyourself,ormakesureIISisconfiguredtoalso run32bitextensions.YoucanusuallyturnthisonbyusingtheIISAdministrationscriptasfollows: Cscript.exeadsutil.vbsSETW3SVC/AppPools/Enable32bitAppOnWin641
WindowsNT/200x/XPandIIS4ornewer
PHPmaybeinstalledasaCGIbinary,orwiththeISAPImodule.Ineithercase,youneedtostartthe MicrosoftManagementConsole(mayappearas'InternetServicesManager',eitherinyourWindowsNT4.0 OptionPackbranchortheControlPanel=>AdministrativeToolsunderWindows2000/XP).Thenrightclick onyourWebservernode(thiswillmostprobablyappearas'DefaultWebServer'),andselect'Properties'. IfyouwanttousetheCGIbinary,dothefollowing:
TousetheISAPImodule,dothefollowing:
Ifyoudon'twanttoperformHTTPAuthenticationusingPHP,youcan(andshould)skipthisstep. UnderISAPIFilters,addanewISAPIfilter.UsePHPasthefiltername,andsupplyapathtothe php4isapi.dll/php5isapi.dll. Under'HomeDirectory','VirtualDirectory',or'Directory',dothefollowing: ChangetheExecutePermissionsto'Scriptsonly' Clickonthe'Configuration'button,andchoosetheApplicationMappingstab.ClickAddandsetthe ExecutablepathtotheappropriateISAPIDLL.AnexamplePHP5valueis:C:\php\php5isapi.dll Supply.phpastheextension.Leave'Methodexclusions'blank,andcheckthe'Scriptengine' checkbox.Now,clickOKafewtimes. StopIIScompletely(NETSTOPiisadmin) StartIISagain(NETSTARTw3svc)
WithIIS6(2003Server),openuptheIISManager,gotoWebServiceExtensions,choose"AddanewWeb serviceextension",enterinanamesuchasPHP,choosetheAddbuttonandforthevaluebrowsetoeitherthe ISAPIfile(php4isapi.dllorphp5isapi.dll)orCGI(php.exeorphpcgi.exe)thencheck"Setextensionstatus toAllowed"andclickOK. Inordertouseindex.phpasadefaultcontentpage,dothefollowing:FromwithintheDocumentstab,choose Add.Typeinindex.phpandclickOK.AdjusttheorderbychoosingMoveUporMoveDown.Thisissimilar tosettingDirectoryIndexwithApache. ThestepsabovemustberepeatedforeachextensionthatistobeassociatedwithPHPscripts..phpisthe mostcommonalthough.php3mayberequiredforlegacyapplications. Ifyouexperience100%CPUusageaftersometime,turnofftheIISsettingCacheISAPIApplication.
WindowsandPWS4
PWS4doesnotsupportISAPI,onlyPHPCGIshouldbeused.
WindowsandPWS/IIS3
TherecommendedmethodforconfiguringtheseserversistousetheREGfileincludedwiththedistribution (pwsphp4cgi.regintheSAPIfolderforPHP4,orpwsphp5cgi.reginthemainfolderforPHP5).Youmay wanttoeditthisfileandmakesuretheextensionsandPHPinstalldirectoriesmatchyourconfiguration.Or youcanfollowthestepsbelowtodoitmanually. Warning ThesestepsinvolveworkingdirectlywiththeWindowsregistry.Oneerrorherecanleaveyoursysteminan unstablestate.Wehighlyrecommendthatyoubackupyourregistryfirst.ThePHPDevelopmentteamwill notbeheldresponsibleifyoudamageyourregistry.
PWSandIIS3usersnowhaveafullyoperationalsystem.IIS3userscanuseaniftytoolfromSteven Genusatoconfiguretheirscriptmaps.
Apache1.3.xonMicrosoftWindows
ThissectioncontainsnotesandhintsspecifictoApache1.3.xinstallsofPHPonMicrosoftWindows systems.TherearealsoinstructionsandnotesforApache2onaseparatepage. Note:Pleasereadthemanualinstallationstepsfirst! TherearetwowaystosetupPHPtoworkwithApache1.3.xonWindows.OneistousetheCGIbinary (php.exeforPHP4andphpcgi.exeforPHP5),theotheristousetheApacheModuleDLL.Ineithercase youneedtoedityourhttpd.conftoconfigureApachetoworkwithPHP,andthenrestarttheserver. ItisworthnotingherethatnowtheSAPImodulehasbeenmademorestableunderWindows,we recommendit'suseabovetheCGIbinary,sinceitismoretransparentandsecure. AlthoughtherecanbeafewvariationsofconfiguringPHPunderApache,thesearesimpleenoughtobeused bythenewcomer.PleaseconsulttheApacheDocumentationforfurtherconfigurationdirectives. Afterchangingtheconfigurationfile,remembertorestarttheserver,forexample,NETSTOPAPACHE followedbyNETSTARTAPACHE,ifyourunApacheasaWindowsService,oruseyourregular shortcuts. Note:RememberthatwhenaddingpathvaluesintheApacheconfigurationfilesonWindows,all backslashessuchasc:\directory\file.extmustbeconvertedtoforwardslashes: c:/directory/file.ext.Atrailingslashmayalsobenecessaryfordirectories.
InstallingasanApachemodule
YoushouldaddthefollowinglinestoyourApachehttpd.conffile: Example#1PHPasanApache1.3.xmodule ThisassumesPHPisinstalledtoc:\php.Adjustthepathifthisisnotthecase. ForPHP4:
ForPHP5:
#AddtotheendoftheLoadModulesection LoadModulephp5_module"C:/php/php5apache.dll" #AddtotheendoftheAddModulesection AddModulemod_php5.c
Forboth:
#Addthislineinsidethe<IfModulemod_mime.c>conditionalbrace AddTypeapplication/xhttpdphp.php #Forsyntaxhighlighted.phpsfiles,alsoadd AddTypeapplication/xhttpdphpsource.phps
InstallingasaCGIbinary
IfyouunzippedthePHPpackagetoC:\php\asdescribedintheManualInstallationStepssection,youneed toinserttheselinestoyourApacheconfigurationfiletosetuptheCGIbinary: Example#2PHPandApache1.3.xasCGI
ScriptAlias/php/"c:/php/" AddTypeapplication/xhttpdphp.php #ForPHP4 Actionapplication/xhttpdphp"/php/php.exe" #ForPHP5 Actionapplication/xhttpdphp"/php/phpcgi.exe" #specifythedirectorywherephp.iniis SetEnvPHPRCC:/php
Apache2.0.xonMicrosoftWindows
ThissectioncontainsnotesandhintsspecifictoApache2.0.xinstallsofPHPonMicrosoftWindows systems.WealsohaveinstructionsandnotesforApache1.3.xusersonaseparatepage. Note:Youshouldreadthemanualinstallationstepsfirst! Note:Apache2.2.xSupport UsersofApache2.2.xmayusethedocumentationbelowexcepttheappropriateDLLfileis namedphp5apache2_2.dllanditonlyexistsasofPHP5.2.0.Seealsohttp://snaps.php.net/ Warning WedonotrecommendusingathreadedMPMinproductionwithApache2.UsethepreforkMPMinstead, oruseApache1.Forinformationonwhy,readtherelatedFAQentryonusingApache2withathreaded MPM YouarehighlyencouragedtotakealookattheApacheDocumentationtogetabasicunderstandingofthe Apache2.0.xServer.AlsoconsidertoreadtheWindowsspecificnotesforApache2.0.xbeforereadingon here. Note:PHPandApache2.0.xcompatibilitynotes ThefollowingversionsofPHPareknowntoworkwiththemostrecentversionofApache2.0.x:
TheseversionsofPHParecompatibletoApache2.0.40andlater. Apache2.0SAPIsupportstartedwithPHP4.2.0.PHP4.2.3workswithApache2.0.39,don'tuse anyotherversionofApachewithPHP4.2.3.However,therecommendedsetupistousePHP 4.3.0orlaterwiththemostrecentversionofApache2. AllmentionedversionsofPHPwillworkstillwithApache1.3.x. Warning Apache2.0.xisdesignedtorunonWindowsNT4.0,Windows2000orWindowsXP.Atthistime,support forWindows9xisincomplete.Apache2.0.xisnotexpectedtoworkonthoseplatformsatthistime. DownloadthemostrecentversionofApache2.0.xandafittingPHPversion.FollowtheManual InstallationStepsandcomebacktogoonwiththeintegrationofPHPandApache. TherearetwowaystosetupPHPtoworkwithApache2.0.xonWindows.OneistousetheCGIbinarythe otheristousetheApachemoduleDLL.Ineithercaseyouneedtoedityourhttpd.conftoconfigureApache
InstallingasaCGIbinary
YouneedtoinsertthesethreelinestoyourApachehttpd.confconfigurationfiletosetuptheCGIbinary: Example#1PHPandApache2.0asCGI
ScriptAlias/php/"c:/php/" AddTypeapplication/xhttpdphp.php #ForPHP4 Actionapplication/xhttpdphp"/php/php.exe" #ForPHP5 Actionapplication/xhttpdphp"/php/phpcgi.exe"
InstallingasanApachemodule
YouneedtoinsertthesetwolinestoyourApachehttpd.confconfigurationfiletosetupthePHPmodulefor Apache2.0: Example#2PHPandApache2.0asModule
#ForPHP4dosomethinglikethis: LoadModulephp4_module"c:/php/php4apache2.dll" #Don'tforgettocopythephp4apache2.dllfilefromthesapidirectory! AddTypeapplication/xhttpdphp.php #ForPHP5dosomethinglikethis: LoadModulephp5_module"c:/php/php5apache2.dll" AddTypeapplication/xhttpdphp.php #configurethepathtophp.ini PHPIniDir"C:/php"
Don'tmixupyourinstallationwithDLLfilesfromdifferentPHPversions.Youhavetheonlychoicetouse theDLL'sandextensionsthatshipwithyourdownloadedPHPversion.
Sun,iPlanetandNetscapeserversonMicrosoftWindows
ThissectioncontainsnotesandhintsspecifictoSunJavaSystemWebServer,SunONEWebServer,iPlanet andNetscapeserverinstallsofPHPonWindows. FromPHP4.3.3onyoucanusePHPscriptswiththeNSAPImoduletogeneratecustomdirectorylistings anderrorpages.AdditionalfunctionsforApachecompatibilityarealsoavailable.Forsupportincurrentweb serversreadthenoteaboutsubrequests.
CGIsetuponSun,iPlanetandNetscapeservers
ToinstallPHPasaCGIhandler,dothefollowing:
Copyphp4ts.dlltoyoursystemroot(thedirectorywhereyouinstalledWindows) Makeafileassociationfromthecommandline.Typethefollowingtwolines:
assoc.php=PHPScript ftypePHPScript=c:\php\php.exe%1%*
MoredetailsaboutsettingupPHPasaCGIexecutablecanbefoundhere: http://benoit.noss.free.fr/php/installphp.html
NSAPIsetuponSun,iPlanetandNetscapeservers
ToinstallPHPwithNSAPI,dothefollowing:
Copyphp4ts.dlltoyoursystemroot(thedirectorywhereyouinstalledWindows) Makeafileassociationfromthecommandline.Typethefollowingtwolines:
assoc.php=PHPScript ftypePHPScript=c:\php\php.exe%1%*
placethelinesaftermimetypesinit.
Initfn="loadmodules"funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll" Initfn="php4_init"LateInit="yes"errorString="FailedtoinitialisePHP!" [php_ini="c:/path/to/php.ini"]
(PHP>=4.3.3)Thephp_iniparameterisoptionalbutwithityoucanplaceyourphp.iniinyourweb serverconfigurationdirectory.
ThisisonlyneededifyouwanttoconfigureadirectorythatonlyconsistsofPHPscripts(samelikea cgibindirectory):
<Objectname="xhttpdphp"> ObjectTypefn="forcetype"type="magnusinternal/xhttpdphp" Servicefn=php4_execute[inikey=valueinikey=value...] </Object>
AfterthatyoucanconfigureadirectoryintheAdministrationserverandassignitthestylexhttpd php.AllfilesinitwillgetexecutedasPHP.ThisisnicetohidePHPusagebyrenamingfilesto.html.
CGIenvironmentandrecommendedmodificationsinphp.ini
ImportantwhenwritingPHPscriptsisthefactthatSunJSWS/SunONEWS/iPlanet/Netscapeisa multithreadedwebserver.Becauseofthatallrequestsarerunninginthesameprocessspace(thespaceofthe webserveritself)andthisspacehasonlyoneenvironment.IfyouwanttogetCGIvariableslike PATH_INFO,HTTP_HOSTetc.itisnotthecorrectwaytotrythisintheoldPHPwaywithgetenv()ora similarway(registerglobalstoenvironment,$_ENV).Youwouldonlygettheenvironmentoftherunning webserverwithoutanyvalidCGIvariables!
Note:Whyarethere(invalid)CGIvariablesintheenvironment? Answer:Thisisbecauseyoustartedthewebserverprocessfromtheadminserverwhichrunsthe startupscriptofthewebserver,youwantedtostart,asaCGIscript(aCGIscriptinsideofthe adminserver!).ThisiswhytheenvironmentofthestartedwebserverhassomeCGIenvironment variablesinit.Youcantestthisbystartingthewebservernotfromtheadministrationserver.Use thecommandlineasrootuserandstartitmanuallyyouwillseetherearenoCGIlike environmentvariables. SimplychangeyourscriptstogetCGIvariablesinthecorrectwayforPHP4.xbyusingthesuperglobal $_SERVER.Ifyouhaveolderscriptswhichuse$HTTP_HOST,etc.,youshouldturnonregister_globalsin php.iniandchangethevariableordertoo(important:remove"E"fromit,becauseyoudonotneedthe environmenthere):
variables_order="GPCS" register_globals=On
Specialuseforerrorpagesorselfmadedirectorylistings(PHP>=4.3.3)
YoucanusePHPtogeneratetheerrorpagesfor"404NotFound"orsimilar.Addthefollowinglinetothe objectinobj.confforeveryerrorpageyouwanttooverwrite:
Errorfn="php4_execute"code=XXXscript="/path/to/script.php"[inikey=value inikey=value...]
ForbotherroranddirectorylistingpagestheoriginalURIandtranslatedURIareinthevariables $_SERVER['PATH_INFO']and$_SERVER['PATH_TRANSLATED'].
Noteaboutnsapi_virtual()andsubrequests(PHP>=4.3.3)
TheNSAPImodulenowsupportsthensapi_virtual()function(alias:virtual())tomakesubrequestsonthe webserverandinserttheresultinthewebpage.Theproblemis,thatthisfunctionusessomeundocumented featuresfromtheNSAPIlibrary. UnderUnixthisisnotaproblem,becausethemoduleautomaticallylooksfortheneededfunctionsanduses themifavailable.Ifnot,nsapi_virtual()isdisabled. UnderWindowslimitationsintheDLLhandlingneedtheuseofaautomaticdetectionofthemostrecentns httpdXX.dllfile.Thisistestedforserverstillversion6.1.IfanewerversionoftheSunserverisused,the detectionfailsandnsapi_virtual()isdisabled.
Ifthisisthecase,trythefollowing:Addthefollowingparametertophp4_initinmagnus.conf/obj.conf:
Initfn=php4_init...server_lib="nshttpdXX.dll"
OmniHTTPdServer
ThissectioncontainsnotesandhintsspecifictoOmniHTTPdonWindows. Note:Youshouldreadthemanualinstallationstepsfirst! Warning AserverdeployedinCGImodeisopentoseveralpossiblevulnerabilities.PleasereadourCGIsecurity sectiontolearnhowtodefendyourselffromsuchattacks. YouneedtocompletethefollowingstepstomakePHPworkwithOmniHTTPd.ThisisaCGIexecutable setup.SAPIissupportedbyOmniHTTPd,butsometestshaveshownthatitisnotsostabletousePHPasan ISAPImodule. Note:ImportantforCGIusers Readthefaqoncgi.force_redirectforimportantdetails.Thisdirectiveneedstobesetto0. 1. InstallOmniHTTPdserver. 2. RightclickontheblueOmniHTTPdiconinthesystemtrayandselectProperties 3. ClickonWebServerGlobalSettings 4. Onthe'External'tab,enter:virtual=.php|actual=c:\php\php.exe(usephpcgi.exeifinstallingPHP 5),andusetheAddbutton. 5. OntheMimetab,enter:virtual=wwwserver/stdcgi|actual=.php,andusetheAddbutton. 6. ClickOK Repeatsteps26foreachextensionyouwanttoassociatewithPHP. Note:SomeOmniHTTPdpackagescomewithbuiltinPHPsupport.Youcanchooseatsetup timetodoacustomsetup,anduncheckthePHPcomponent.Werecommendyoutousethelatest
SambarServeronMicrosoftWindows
ThissectioncontainsnotesandhintsspecifictotheSambarServerforWindows. Note:Youshouldreadthemanualinstallationstepsfirst! ThislistdescribeshowtosetuptheISAPImoduletoworkwiththeSambarserveronWindows.
(ThislineassumesthatPHPwasinstalledinc:\php.)
XitamionMicrosoftWindows
ThissectioncontainsnotesandhintsspecifictoXitamionWindows. Note:Youshouldreadthemanualinstallationstepsfirst! ThislistdescribeshowtosetupthePHPCGIbinarytoworkwithXitamionWindows.
Buildingfromsource
ThischapterteacheshowtocompilePHPfromsourcesonwindows,usingMicrosoft'stools.Tocompile PHPwithcygwin,pleaserefertoInstallationonUnixsystems.
QuickGuidetoBuildingOnWindows
ThisstepbystepquickstartguidewaswritteninMarchof2008,runningWindowsXPServicePack2with allthelatestupdatesandbuildingPHP5.2.5andPHP5.3.Experiencesusingdifferenttoolsmaydiffer. 1. Downloadandinstall: MicrosoftVisualC++2008ExpressEdition WindowsSDKforWindowsServer2008and.NETFramework3.5 CopyC:\ProgramFiles\MicrosoftSDKs\Windows\v6.1\Include\WinResrc.htoC:\Program Files\MicrosoftSDKs\Windows\v6.1\Include\winres.h. CreatethedirectoryC:\work. DownloadtheWindowsbuildtoolsandunzipthecontentsintoC:\work. CreatethedirectoryC:\usr\local\lib.CopytheC:\work\win32build\bin\bison.simpleintothenew directory. DownloadtheWindowsDNSresolverlibraryandunzipthecontentsintoC:\work. OpenC:\work\bindlib_w32\bindlib.dsw.Ifandwhenaskedwhethertoupdatetheproject,chooseYes. ChooseeitherDebugorReleaseconfigurationinthetoptoolbar,thenchooseBuild=>Build
2. 3. 4. 5. 6. 7.
9. OpenashellusingtheVisualStudio2008CommandPromptshortcutintheStartmenu. 10.Executethecommand:
C:\ProgramFiles\MicrosoftVisualStudio9.0\VC>set "PATH=C:\work\win32build\bin;%PATH%" C:\ProgramFiles\MicrosoftVisualStudio9.0\VC>
BuildEnvironment
TocompileandbuildPHPyouneedaMicrosoftDevelopmentEnvironment.Thefollowingenvironmentsare supported:
Thereareafewpostinstallationsteps:
Libraries
ToextractthedownloadedfilesyouwillalsoneedaZIPextractionutility.WindowsXPandneweralready includethisfunctionalitybuiltin. Beforeyougetstarted,youhavetodownload:
Finally,youaregoingtoneedthesourcetoPHPitself.Youcangetthelatestdevelopmentversionusing anonymousCVS,asnapshotorthemostrecentreleasedsourcetarball.
Puttingitalltogether
Afterdownloadingtherequiredpackagesyouhavetoextracttheminaproperplace:
Followingthisstepsyourdirectorystructurelookslikethis:
+C:\work || |+bindlib_w32 ||| ||+arpa ||| ||+conf ||| ||+... || |+php5.x.x ||| ||+build ||| ||+... ||| ||+win32 ||| ||+... || |+win32build ||| ||+bin ||| ||+include ||| ||+lib
Buildresolv.lib
Youmustbuildtheresolv.liblibrary.Decidewhetheryouwanttohavedebugsymbolsavailable(bindlib Win32Debug)ornot(bindlibWin32Release),butpleaserememberthechoiceyoumade,becausethe debugbuildwillonlylinkwithPHPwhenitisalsobuiltindebugmode.Buildtheappropriateconfiguration:
msdevbindlib.dsp/MAKE"bindlibWin32Release"
BuildingPHPusingthenewbuildsystem[PHP>=5only]
ThischapterexplainshowtocompilePHP>=5usingthenewbuildsystem,whichisCLIbasedandvery similarwiththemainPHP'sUnixbuildsystem. Note:Thisbuildsystemisn'tavailableinPHP4.PleaserefertoBuildingfromsourceinstead. Beforestarting,besureyouhavereadBuildingfromsourceandyouhavebuiltallneededlibraries,like LibxmlorICU(neededforPHP>=6). FirstyoushouldopenaVisualStudioCommandPrompt,whichshouldbeavailableundertheStartmenu.A regularCommandPromptwindowshouldn'twork,asprobablyitdoesn'thavethenecessaryenvironment variablesset.ThentypesomethinglikecdC:\work\php5.x.xtoenterinthePHPsourcedir.Nowyouare readytostartconfiguringPHP. Thesecondstepisrunningthebuildconfbatchfiletomaketheconfigurescript,byscanningthefolderfor config.w32files.Bydefaultthiscommandwillalsosearchinthefollowingdirectories:pecl;..\pecl; pecl\rpc;..\pecl\rpc.SincePHP5.1.0,youcanchangethisbehaviourbyusingtheaddmodulesdir argument(e.g.cscript/nologowin32/build/buildconf.jsaddmodulesdir=../phpgtk2addmodules dir=../pecl). Thethirdstepisconfiguring.Toviewthelistoftheavailableconfigurationoptionstypecscript/nologo configure.jshelp.Afterchoosingtheoptionsthatyouwillenable/disable,typesomethinglike:cscript /nologoconfigure.jsdisablefooenablefunext.Usingenablefoo=sharedwillattempttobuildthe 'foo'extensionasashared,dynamicallyloadablemodule. Thelaststepiscompiling.Toachievethisjustissuethecommandnmake.Thegeneratedfiles(e.g..exe and.dll)willbeplacedineitherRelease_TSorDebug_TSdirectories(ifbuiltwithThreadsafety),orinthe ReleaseorDebugdirectoriesotherwise. OptionallyyoumayalsorunPHP'stestsuite,bytypingnmaketest.Ifyouwanttorunjustaspecifictest, youmayusethe'TESTS'variable(e.g.nmake/DTESTS=ext/sqlite/teststestwillonlyrunsqlite'stests). Todeletethefilesthatwerecreatedduringthecompilation,youcanusethenmakecleancommand. Averyusefulconfigureoptiontobuildsnapshotsisenablesnapshotbuild,whichaddanewcompiling mode(nmakebuildsnap).Thistriestobuildeveryextensionavailable(asshared,bydefault),butitwill ignorebuilderrorsinindividualextensionsorSAPI.
BuildingPHPusingDSWfiles[PHP4]
CompilingPHPusingtheDSWfilesisn'tsupportedasofPHP5,asamuchmoreflexiblesystemwasmade
Compiling ThebestwaytogetstartedistobuildtheCGIversion:
ForGUIusers,launchVC++,andthenselectFile=>OpenWorkspaceandselectC:\work\php4.x.x\ win32\php4ts.dsw.ThenselectBuild=>SetActiveConfigurationandselectthedesiredconfiguration, eitherphp4tsWin32Debug_TSorphp4tsWin32Release_TS.FinallyselectBuild=>RebuildAll. Forcommandlineusers,makesurethatyoueitherhavetheC++environmentvariablesregistered,or haverunvcvars.bat,andthenexecuteoneofthefollowingcommandsfromthe C:\work\php4.x.x\win32directory: msdevphp4ts.dsp/MAKE"php4tsWin32Debug_TS" msdevphp4ts.dsp/MAKE"php4tsWin32Release_TS" Atthispoint,youshouldhaveausablephp.exeineitheryourC:\work\php4.x.x\Debug_TSor Release_TSsubdirectories.
InstallationofextensionsonWindows
AfterinstallingPHPandawebserveronWindows,youwillprobablywanttoinstallsomeextensionsfor addedfunctionality.YoucanchoosewhichextensionsyouwouldliketoloadwhenPHPstartsbymodifying
yourphp.ini.Youcanalsoloadamoduledynamicallyinyourscriptusingdl(). TheDLLsforPHPextensionsareprefixedwithphp_. ManyextensionsarebuiltintotheWindowsversionofPHP.ThismeansadditionalDLLfiles,andthe extensiondirective,arenotusedtoloadtheseextensions.TheWindowsPHPExtensionstablelists extensionsthatrequire,orusedtorequire,additionalPHPDLLfiles.Here'salistofbuiltinextensions: InPHP4(updatedPHP4.3.11):BCMath,Caledar,COM,Ctype,FTP,MySQL,ODBC,Overload,PCRE, Session,Tokenizer,WDDX,XMLandZlib InPHP5(updatedPHP5.0.4),thefollowingchangesexist.Builtin:DOM,LibXML,Iconv,SimpleXML, SPLandSQLite.Andthefollowingarenolongerbuiltin:MySQLandOverload. ThedefaultlocationPHPsearchesforextensionsisC:\php4\extensionsinPHP4andC:\php5inPHP5.To changethissettingtoreflectyoursetupofPHPedityourphp.inifile:
Youwillneedtochangetheextension_dirsettingtopointtothedirectorywhereyourextensions lives,orwhereyouhaveplacedyourphp_*.dllfiles.Forexample:
extension_dir=C:\php\extensions
SomeoftheextensionsneedextraDLLstowork.Coupleofthemcanbefoundinthedistribution package,intheC:\php\dlls\folderinPHP4orinthemainfolderinPHP5,butsome,forexample Oracle(php_oci8.dll)requireDLLswhicharenotbundledwiththedistributionpackage.Ifyouare installingPHP4,copythebundledDLLsfromC:\php\dllsfoldertothemainC:\phpfolder.Don't forgettoincludeC:\phpinthesystemPATH(thisprocessisexplainedinaseparateFAQentry). SomeoftheseDLLsarenotbundledwiththePHPdistribution.Seeeachextensionsdocumentation pagefordetails.Also,readthemanualsectiontitledInstallationofPECLextensionsfordetailson PECL.AnincreasinglylargenumberofPHPextensionsarefoundinPECL,andtheseextensions requireaseparatedownload. Note:IfyouarerunningaservermoduleversionofPHPremembertorestartyourwebserverto reflectyourchangestophp.ini.
Thefollowingtabledescribessomeoftheextensionsavailableandrequiredadditionaldlls. PHPExtensions
Extension php_bz2.dll
Notes
Extension
Description
Notes
php_calendar.dll Calendarconversionfunctions BuiltinsincePHP4.0.3 php_crack.dll php_ctype.dll php_curl.dll Crackfunctions ctypefamilyfunctions CURL,ClientURLlibrary functions DBA:DataBase(dbmstyle) Abstractionlayerfunctions dBasefunctions dbxfunctions None BuiltinsincePHP4.3.0 Requires:libeay32.dll,ssleay32.dll(bundled)
None None PHP<=4.2.0requires:libxml2.dll(bundled)PHP>= 4.3.0requires:iconv.dll(bundled) PHP<=4.1.1 php_mbstring.dll.And,php_exif.dllmustbeloadedafter php_mbstring.dllinphp.ini. PHP<=4.2.0 Requires:fdftk.dll(bundled) Readonlyaccess BuiltinsincePHP4.0.3 RemovedinPHP4.3.2.Alsonotethattruecolorfunctions arenotavailableinGD1,instead,usephp_gd2.dll. GD2 PHP<=4.2.0requiresgnu_gettext.dll(bundled),PHP>= 4.2.3requireslibintl1.dll,iconv.dll(bundled).
php_domxml.dll DOMXMLfunctions php_dotnet.dll php_exif.dll php_fbsql.dll php_fdf.dll php_filepro.dll php_ftp.dll php_gd.dll php_gd2.dll php_gettext.dll .NETfunctions EXIFfunctions FrontBasefunctions FDF:FormsDataFormat functions. fileProfunctions FTPfunctions GDlibraryimagefunctions GDlibraryimagefunctions Gettextfunctions
Extension
Description None
Notes
php_hyperwave.d HyperWavefunctions ll php_iconv.dll php_ifx.dll php_iisfunc.dll php_imap.dll php_ingres.dll ICONVcharacterset conversion Informixfunctions IISmanagementfunctions IMAPPOP3andNNTP functions IngresIIfunctions
Requires:iconv1.3.dll(bundled),PHP>=4.2.1iconv.dll Requires:Informixlibraries None None Requires:IngresIIlibraries Requires:gds32.dll(bundled) PHP<=4.0.6requires:jvm.dll(bundled) PHP<=4.2.0requireslibsasl.dll(bundled),PHP>=4.3.0 requireslibeay32.dll,ssleay32.dll(bundled) None Requires:libmcrypt.dll PHP>=4.3.0requires:libmhash.dll(bundled) Requires:magic.mime(bundled) None Requires:msql.dll(bundled) Requires:ntwdblib.dll(bundled) PHP>=5.0.0,requireslibmysql.dll(bundled) PHP>=5.0.0,requireslibmysql.dll(libmysqli.dllinPHP
php_mime_magic Mimetypefunctions .dll php_ming.dll php_msql.dll php_mssql.dll php_mysql.dll php_mysqli.dll MingfunctionsforFlash mSQLfunctions MSSQLfunctions MySQLfunctions MySQLifunctions
Extension
Description <=5.0.2)(bundled)
Notes
php_oci8.dll php_openssl.dll
Oracle8functions OpenSSLfunctions
php_overload.dll Objectoverloadingfunctions php_pdf.dll php_pgsql.dll php_printer.dll php_shmop.dll php_snmp.dll php_soap.dll php_sockets.dll PDFfunctions PostgreSQLfunctions Printerfunctions SharedMemoryfunctions
SNMPgetandwalkfunctions NTonly! SOAPfunctions Socketfunctions PHP>=5.0.0 None Requires:Sybaseclientlibraries PHP>=5.0.0 BuiltinsincePHP4.3.0 None PHP>=4.2.1requires:iconv.dll(bundled) PHP<=4.2.0requiressablot.dll,expat.dll(bundled). PHP>=4.2.1requiressablot.dll,expat.dll,iconv.dll (bundled). Requires:yaz.dll(bundled) Readonlyaccess
php_xslt.dll
XSLTfunctions
php_yaz.dll php_zip.dll
YAZfunctions ZipFilefunctions
Extension php_zlib.dll
Notes
InstallationofPECLextensions
TableofContents
IntroductiontoPECLInstallations
PECLisarepositoryofPHPextensionsthataremadeavailabletoyouviathePEARpackagingsystem. ThissectionofthemanualisintendedtodemonstratehowtoobtainandinstallPECLextensions. Theseinstructionsassume/your/phpsrcdir/isthepathtothePHPsourcedistribution,andthatextnameisthe nameofthePECLextension.Adjustaccordingly.Theseinstructionsalsoassumeafamiliaritywiththepear command.TheinformationinthePEARmanualforthepearcommandalsoappliestothepeclcommand. Tobeuseful,asharedextensionmustbebuilt,installed,andloaded.Themethodsdescribedbelowprovide youwithvariousinstructionsonhowtobuildandinstalltheextensions,buttheydonotautomaticallyload them.Extensionscanbeloadedbyaddinganextensiondirective.Tothisphp.inifile,orthroughtheuseof thedl()function. WhenbuildingPHPmodules,it'simportanttohaveknowngoodversionsoftherequiredtools(autoconf, automake,libtool,etc.)SeetheAnonymousCVSInstructionsfordetailsontherequiredtools,andrequired versions.
DownloadingPECLextensions
ThereareseveraloptionsfordownloadingPECLextensions,suchas:
InstallingaPHPextension
OnWindows,youhavetwowaystoloadaPHPextension:eithercompileitintoPHP,orloadtheDLL. Loadingaprecompiledextensionistheeasiestandpreferredway. Toloadanextension,youneedtohaveitavailableasa".dll"fileonyoursystem.Alltheextensionsare automaticallyandperiodicallycompiledbythePHPGroup(seenextsectionforthedownload). TocompileanextensionintoPHP,pleaserefertobuildingfromsourcedocumentation. Tocompileastandaloneextension(akaaDLLfile),pleaserefertobuildingfromsourcedocumentation.If theDLLfileisavailableneitherwithyourPHPdistributionnorinPECL,youmayhavetocompileitbefore youcanstartusingtheextension.
Wheretofindanextension?
PHPextensionsareusuallycalled"php_*.dll"(wherethestarrepresentsthenameoftheextension)andthey arelocatedunderthe"PHP\ext"("PHP\extensions"inPHP4)folder. PHPshipswiththeextensionsmostusefultothemajorityofdevelopers.Theyarecalled"core"extensions. However,ifyouneedfunctionnalitynotprovidedbyanycoreextension,youmaystillbeabletofindonein PECL.ThePHPExtensionCommunityLibrary(PECL)isarepositoryforPHPExtensions,providinga directoryofallknownextensionsandhostingfacilitiesfordownloadinganddevelopmentofPHPextensions.
Whichextensiontodownload?
Manytimes,youwillfindseveralversionsofeachDLL:
YoushouldkeepinmindthatyourextensionsettingsshouldmatchallthesettingsofthePHPexecutableyou areusing.ThefollowingPHPscriptwilltellyouallaboutyourPHPsettings:
<?php phpinfo(); ?>
Orfromthecommandline,run:
drive:\\path\to\php\executable\php.exei
Loadinganextension
ThemostcommonwaytoloadaPHPextensionistoincludeitinyourphp.iniconfigurationfile.Pleasenote thatmanyextensionsarealreadypresentinyourphp.iniandthatyouonlyneedtoremovethesemicolonto activatethem.
;extension=php_extname.dll extension=php_extname.dll
However,somewebserversareconfusingbecausetheydonotusethephp.inilocatedalongsideyourPHP executable.Tofindoutwhereyouractualphp.iniresides,lookforitspathinphpinfo():
ConfigurationFile(php.ini)PathC:\WINDOWS LoadedConfigurationFileC:\ProgramFiles\PHP\5.2\php.ini
Afteractivatinganextension,savephp.ini,restartthewebserverandcheckphpinfo()again.Thenew extensionshouldnowhaveitsownsection.
Resolvingproblems
Iftheextensiondoesnotappearinphpinfo(),youshouldcheckyourlogstolearnwheretheproblemcomes
from. IfyouareusingPHPfromthecommandline(CLI),theextensionloadingerrorcanbereaddirectlyon screen. IfyouareusingPHPwithawebserver,thelocationandformatofthelogsvarydependingonyoursoftware. Pleasereadyourwebserverdocumentationtolocatethelogs,asitdoesnothaveanythingtodowithPHP itself. CommonproblemsarethelocationoftheDLL,thevalueofthe"extension_dir"settinginsidephp.iniand compiletimesettingmismatches. Iftheproblemliesinacompiletimesettingmismatch,youprobablydidn'tdownloadtherightDLL.Try downloadingagaintheextensionwiththerightsettings.Again,phpinfo()canbeofgreathelp.
CompilingsharedPECLextensionswiththepeclcommand
PECLmakesiteasytocreatesharedPHPextensions.Usingthepeclcommand,dothefollowing:
$peclinstallextname
Youmayalsoinstallaspecificversionusingthisvariant:
$peclinstallextname0.1
Note:Afterenablingtheextensioninphp.ini,restartingthewebserviceisrequiredforthe changestobepickedup.
CompilingsharedPECLextensionswithphpize
Sometimes,usingthepeclinstallerisnotanoption.Thiscouldbebecauseyou'rebehindafirewall,orit couldbebecausetheextensionyouwanttoinstallisnotavailableasaPECLcompatiblepackage,suchas
CompilingPECLextensionsstaticallyintoPHP
YoumightfindthatyouneedtobuildaPECLextensionstaticallyintoyourPHPbinary.Todothis,you'll needtoplacetheextensionsourceunderthephpsrc/ext/directoryandtellthePHPbuildsystemto regenerateitsconfigurescript.
$cd/your/phpsrcdir/ext $pecldownloadextname $gzipd<extname.tgz|tarxvf $mvextnamex.x.xextname
Thiswillresultinthefollowingdirectory:
/your/phpsrcdir/ext/extname
Fromhere,forcePHPtorebuildtheconfigurescript,andthenbuildPHPasnormal:
$cd/your/phpsrcdir $rmconfigure $./buildconfforce $./configurehelp $./configurewithextnameenablesomeotherextwithfoobar $make $makeinstall
Note:Torunthe'buildconf'scriptyouneedautoconf2.13andautomake1.4+(newerversionsof autoconfmaywork,butarenotsupported).
Whetherenableextnameorwithextnameisuseddependsontheextension.Typicallyanextensionthat doesnotrequireexternallibrariesusesenable.Tobesure,runthefollowingafterbuildconf:
$./configurehelp|grepextname
Problems?
TableofContents
Otherproblems Bugreports
ReadtheFAQ
Someproblemsaremorecommonthanothers.ThemostcommononesarelistedinthePHPFAQ,partof thismanual.
Otherproblems
Ifyouarestillstuck,someoneonthePHPinstallationmailinglistmaybeabletohelpyou.Youshouldcheck outthearchivefirst,incasesomeonealreadyansweredsomeoneelsewhohadthesameproblemasyou.The archivesareavailablefromthesupportpageonhttp://www.php.net/support.php.TosubscribetothePHP installationmailinglist,sendanemptymailtophpinstallsubscribe@lists.php.net.Themailinglistaddress isphpinstall@lists.php.net. Ifyouwanttogethelponthemailinglist,pleasetrytobepreciseandgivethenecessarydetailsaboutyour environment(whichoperatingsystem,whatPHPversion,whatwebserver,ifyouarerunningPHPasCGIor aservermodule,safemode,etc.),andpreferablyenoughcodetomakeothersabletoreproduceandtestyour problem.
Bugreports
IfyouthinkyouhavefoundabuginPHP,pleasereportit.ThePHPdevelopersprobablydon'tknowabout
RuntimeConfiguration
TableofContents
Howtochangeconfigurationsettings
Theconfigurationfile
Theconfigurationfile(php.ini)isreadwhenPHPstartsup.FortheservermoduleversionsofPHP,this happensonlyoncewhenthewebserverisstarted.FortheCGIandCLIversion,ithappensonevery invocation. php.iniissearchedintheselocations(inorder):
SAPImodulespecificlocation(PHPIniDirdirectiveinApache2,ccommandlineoptioninCGIand CLI,php_iniparameterinNSAPI,PHP_INI_PATHenvironmentvariableinTHTTPD) ThePHPRCenvironmentvariable.BeforePHP5.2.0thiswascheckedaftertheregistrykey mentionedbelow. AsofPHP5.2.0,thefollowingregistrylocationsaresearchedinorder: HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z\IniFilePath, HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y\IniFilePathand HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x\IniFilePath,wherex,yandzmeanthePHPmajor, minorandreleaseversions. HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath(WindowsRegistrylocation) Currentworkingdirectory(exceptCLI) Thewebserver'sdirectory(forSAPImodules),ordirectoryofPHP(otherwiseinWindows) Windowsdirectory(C:\windowsorC:\winnt)(forWindows),orwithconfigfilepathcompiletime option
IfphpSAPI.iniexists(whereSAPIisusedSAPI,sothefilenameise.g.phpcli.iniorphpapache.ini),it's usedinsteadofphp.ini.SAPInamecanbedeterminedbyphp_sapi_name(). Note:TheApachewebserverchangesthedirectorytorootatstartupcausingPHPtoattemptto readphp.inifromtherootfilesystemifitexists. Thephp.inidirectiveshandledbyextensionsaredocumentedrespectivelyonthepagesoftheextensions themselves.Thelistofthecoredirectivesisavailableintheappendix.ProbablynotallPHPdirectivesare documentedinthemanualthough.ForacompletelistofdirectivesavailableinyourPHPversion,please readyourwellcommentedphp.inifile.Alternatively,youmayfindthethelatest php.ini fromCVShelpful too. Example#1php.iniexample
;anytextonalineafteranunquotedsemicolon(;)isignored [php];sectionmarkers(textwithinsquarebrackets)arealsoignored ;Booleanvaluescanbesettoeither: ;true,on,yes ;orfalse,off,no,none register_globals=off track_errors=yes ;youcanenclosestringsindoublequotes include_path=".:/usr/local/lib/php" ;backslashesaretreatedthesameasanyothercharacter include_path=".;c:\php\lib"
SincePHP5.1.0,itispossibletorefertoexisting.inivariablesfromwithin.inifiles.Example:open_basedir =${open_basedir}":/new/dir".
Howtochangeconfigurationsettings
RunningPHPasanApachemodule
WhenusingPHPasanApachemodule,youcanalsochangetheconfigurationsettingsusingdirectivesin Apacheconfigurationfiles(e.g.httpd.conf)and.htaccessfiles.Youwillneed"AllowOverrideOptions"or "AllowOverrideAll"privilegestodoso. ThereareseveralApachedirectivesthatallowyoutochangethePHPconfigurationfromwithintheApache configurationfiles.ForalistingofwhichdirectivesarePHP_INI_ALL,PHP_INI_PERDIR,or PHP_INI_SYSTEM,havealookattheListofphp.inidirectivesappendix. php_valuenamevalue Setsthevalueofthespecifieddirective.CanbeusedonlywithPHP_INI_ALLand PHP_INI_PERDIRtypedirectives.Toclearapreviouslysetvalueusenoneasthevalue. Note:Don'tusephp_valuetosetbooleanvalues.php_flag(seebelow)shouldbe
usedinstead. php_flagnameon|off Usedtosetabooleanconfigurationdirective.CanbeusedonlywithPHP_INI_ALLand PHP_INI_PERDIRtypedirectives. php_admin_valuenamevalue Setsthevalueofthespecifieddirective.Thiscannotbeusedin.htaccessfiles.Anydirectivetypeset withphp_admin_valuecannotbeoverriddenby.htaccess.Toclearapreviouslysetvalueuse noneasthevalue. php_admin_flagnameon|off Usedtosetabooleanconfigurationdirective.Thiscannotbeusedin.htaccessfiles.Anydirectivetype setwithphp_admin_flagcannotbeoverriddenby.htaccess. Example#1Apacheconfigurationexample
<IfModulemod_php5.c> php_valueinclude_path".:/usr/local/lib/php" php_admin_flagsafe_modeon </IfModule> <IfModulemod_php4.c> php_valueinclude_path".:/usr/local/lib/php" php_admin_flagsafe_modeon </IfModule>
ChangingPHPconfigurationviatheWindowsregistry
WhenrunningPHPonWindows,theconfigurationvaluescanbemodifiedonaperdirectorybasisusingthe Windowsregistry.TheconfigurationvaluesarestoredintheregistrykeyHKLM\SOFTWARE\PHP\Per DirectoryValues,inthesubkeyscorrespondingtothepathnames.Forexample,configurationvaluesforthe directoryc:\inetpub\wwwrootwouldbestoredinthekeyHKLM\SOFTWARE\PHP\PerDirectory Values\c\inetpub\wwwroot.Thesettingsforthedirectorywouldbeactiveforanyscriptrunningfromthis directoryoranysubdirectoryofit.ThevaluesunderthekeyshouldhavethenameofthePHPconfiguration directiveandthestringvalue.PHPconstantsinthevaluesarenotparsed.However,onlyconfiguration valueschangeableinPHP_INI_USERcanbesetthisway,PHP_INI_PERDIRvaluescannot.
OtherinterfacestoPHP
RegardlessofhowyourunPHP,youcanchangecertainvaluesatruntimeofyourscriptsthroughini_set(). Seethedocumentationontheini_set()pageformoreinformation.
GeneralInstallationConsiderations InstallationonUnixsystems Apache2.0onUnixsystems Lighttpd1.4onUnixsystems Caudium fhttpdrelatednotes Sun,iPlanetandNetscapeserversonSunSolaris CGIandcommandlinesetups HPUXspecificinstallationnotes OpenBSDinstallationnotes Solarisspecificinstallationtips DebianGNU/Linuxinstallationnotes InstallationonMacOSX UsingthebundledPHP CompilingforOSXServer InstallingforApacheonMacOSXClient InstallationonWindowssystems WindowsInstaller(PHP5.1.0andearlier) ManualInstallationSteps ActiveScript MicrosoftIIS/PWS Apache1.3.xonMicrosoftWindows Apache2.0.xonMicrosoftWindows Sun,iPlanetandNetscapeserversonMicrosoftWindows OmniHTTPdServer SambarServeronMicrosoftWindows XitamionMicrosoftWindows Buildingfromsource InstallationofextensionsonWindows InstallationofPECLextensions DownloadingPECLextensions InstallingaPHPextension Wheretofindanextension? CompilingsharedPECLextensionswiththepeclcommand CompilingsharedPECLextensionswithphpize CompilingPECLextensionsstaticallyintoPHP Problems? Otherproblems Bugreports RuntimeConfiguration Howtochangeconfigurationsettings
LanguageReference Basicsyntax
TableofContents
Instructionseparation Comments
EscapingfromHTML
WhenPHPparsesafile,itlooksforopeningandclosingtags,whichtellPHPtostartandstopinterpreting thecodebetweenthem.Parsinginthismannerallowsphptobeembeddedinallsortsofdifferentdocuments, aseverythingoutsideofapairofopeningandclosingtagsisignoredbythePHPparser.Mostofthetime youwillseephpembeddedinHTMLdocuments,asinthisexample. <p>Thisisgoingtobeignored.</p> <?phpecho'Whilethisisgoingtobeparsed.';?> <p>Thiswillalsobeignored.</p> Youcanalsousemoreadvancedstructures: Example#1Advancedescaping <?php if($expression){ ?> <strong>Thisistrue.</strong> <?php }else{ ?> <strong>Thisisfalse.</strong> <?php } ?> Thisworksasexpected,becausewhenPHPhitsthe?>closingtags,itsimplystartsoutputtingwhateverit finds(exceptforanimmediatelyfollowingnewlineseeinstructionseparation)untilithitsanotheropening tag.Theexamplegivenhereiscontrived,ofcourse,butforoutputtinglargeblocksoftext,droppingoutof PHPparsingmodeisgenerallymoreefficientthansendingallofthetextthroughecho()orprint(). Therearefourdifferentpairsofopeningandclosingtagswhichcanbeusedinphp.Twoofthose,<?php?> and<scriptlanguage="php"></script>,arealwaysavailable.TheothertwoareshorttagsandASPstyle tags,andcanbeturnedonandofffromthephp.iniconfigurationfile.Assuch,whilesomepeoplefindshort
tagsandASPstyletagsconvenient,theyarelessportable,andgenerallynotrecommended. Note:AlsonotethatifyouareembeddingPHPwithinXMLorXHTMLyouwillneedtousethe <?php?>tagstoremaincompliantwithstandards. Example#2PHPOpeningandClosingTags 1.<?phpecho'ifyouwanttoserveXHTMLorXMLdocuments,dolikethis ';?> 2.<scriptlanguage="php"> echo'someeditors(likeFrontPage)don\'t likeprocessinginstructions'; </script> 3.<?echo'thisisthesimplest,anSGMLprocessinginstruction';?> <?=expression?>Thisisashortcutfor"<?echoexpression?>" 4.<%echo'YoumayoptionallyuseASPstyletags';%> <%=$variable;#Thisisashortcutfor"<%echo..."%> Whilethetagsseeninexamplesoneandtwoarebothalwaysavailable,exampleoneisthemostcommonly used,andrecommended,ofthetwo. Shorttags(examplethree)areonlyavailablewhentheyareenabledviatheshort_open_tagphp.ini configurationfiledirective,orifphpwasconfiguredwiththeenableshorttagsoption. ASPstyletags(examplefour)areonlyavailablewhentheyareenabledviatheasp_tagsphp.ini configurationfiledirective. Note:Usingshorttagsshouldbeavoidedwhendevelopingapplicationsorlibrariesthatare meantforredistribution,ordeploymentonPHPserverswhicharenotunderyourcontrol, becauseshorttagsmaynotbesupportedonthetargetserver.Forportable,redistributablecode, besurenottouseshorttags.
Instructionseparation
AsinCorPerl,PHPrequiresinstructionstobeterminatedwithasemicolonattheendofeachstatement. TheclosingtagofablockofPHPcodeautomaticallyimpliesasemicolon;youdonotneedtohavea semicolonterminatingthelastlineofaPHPblock.Theclosingtagfortheblockwillincludetheimmediately trailingnewlineifoneispresent. <?php echo'Thisisatest'; ?> <?phpecho'Thisisatest'?> <?phpecho'Weomittedthelastclosingtag';
Comments
PHPsupports'C','C++'andUnixshellstyle(Perlstyle)comments.Forexample: <?php echo'Thisisatest';//Thisisaonelinec++stylecomment /*Thisisamultilinecomment yetanotherlineofcomment*/ echo'Thisisyetanothertest'; echo'OneFinalTest';#Thisisaonelineshellstylecomment ?> The"oneline"commentstylesonlycommenttotheendofthelineorthecurrentblockofPHPcode, whichevercomesfirst.ThismeansthatHTMLcodeafter//...?>or#...?>WILLbeprinted:?>breaksout ofPHPmodeandreturnstoHTMLmode,and//or#cannotinfluencethat.Iftheasp_tagsconfiguration directiveisenabled,itbehavesthesamewith//%>and#%>.However,the</script>tagdoesn'tbreakout ofPHPmodeinaonelinecomment. <h1>Thisisan<?php#echo'simple';?>example.</h1> <p>Theheaderabovewillsay'Thisisanexample'.</p> 'C'stylecommentsendatthefirst*/encountered.Makesureyoudon'tnest'C'stylecomments.Itiseasyto makethismistakeifyouaretryingtocommentoutalargeblockofcode. <?php /* echo'Thisisatest';/*Thiscommentwillcauseaproblem*/ */ ?>
Types
TableofContents
Booleans Integers Floatingpointnumbers Strings Arrays Objects Resources NULL Pseudotypesandvariablesusedinthisdocumentation TypeJuggling
Introduction
PHPsupportseightprimitivetypes. Fourscalartypes:
Twocompoundtypes:
array object
Andfinallytwospecialtypes:
resource NULL
Thismanualalsointroducessomepseudotypesforreadabilityreasons:
Thetypeofavariableisnotusuallysetbytheprogrammer;rather,itisdecidedatruntimebyPHPdepending onthecontextinwhichthatvariableisused. Note:Tocheckthetypeandvalueofanexpression,usethevar_dump()function.Togeta humanreadablerepresentationofatypefordebugging,usethegettype()function.Tocheckfora certaintype,donotusegettype(),butrathertheis_typefunctions.Someexamples: <?php $a_bool=TRUE;//aboolean $a_str="foo";//astring $a_str2='foo';//astring $an_int=12;//aninteger echogettype($a_bool);//printsout:boolean echogettype($a_str);//printsout:string //Ifthisisaninteger,incrementitbyfour if(is_int($an_int)){ $an_int+=4; } //If$boolisastring,printitout //(doesnotprintoutanything) if(is_string($a_bool)){ echo"String:$a_bool"; } ?> Toforciblyconvertavariabletoacertaintype,eithercastthevariableorusethesettype()functiononit. Notethatavariablemaybeevaluatedwithdifferentvaluesincertainsituations,dependingonwhattypeitis atthetime.Formoreinformation,seethesectiononTypeJuggling.Thetypecomparisontablesmayalsobe useful,astheyshowexamplesofvarioustyperelatedcomparisons.
Booleans
Thisisthesimplesttype.Abooleanexpressesatruthvalue.ItcanbeeitherTRUEorFALSE. Note:ThebooleantypewasintroducedinPHP4.
Syntax
Tospecifyabooleanliteral,usethekeywordsTRUEorFALSE.Botharecaseinsensitive. <?php $foo=True;//assignthevalueTRUEto$foo ?> Typically,somekindofoperatorwhichreturnsabooleanvalue,andthevalueispassedontoacontrol
structure. <?php //==isanoperatorwhichtest //equalityandreturnsaboolean if($action=="show_version"){ echo"Theversionis1.23"; } //thisisnotnecessary... if($show_separators==TRUE){ echo"<hr>\n"; } //...becauseinstead,thiscanbeused: if($show_separators){ echo"<hr>\n"; } ?>
Convertingtoboolean
Toexplicitlyconvertavaluetoboolean,usethe(bool)or(boolean)casts.However,inmostcasesthecastis unncecessary,sinceavaluewillbeautomaticallyconvertedifanoperator,functionorcontrolstructure requiresabooleanargument. SeealsoTypeJuggling. Whenconvertingtoboolean,thefollowingvaluesareconsideredFALSE:
EveryothervalueisconsideredTRUE(includinganyresource). Warning 1isconsideredTRUE,likeanyothernonzero(whethernegativeorpositive)number! <?php var_dump((bool)"");//bool(false) var_dump((bool)1);//bool(true) var_dump((bool)2);//bool(true) var_dump((bool)"foo");//bool(true) var_dump((bool)2.3e5);//bool(true) var_dump((bool)array(12));//bool(true) var_dump((bool)array());//bool(false)
var_dump((bool)"false");//bool(true) ?>
Integers
AnintegerisanumberofthesetZ={...,2,1,0,1,2,...}. Seealso:
Syntax
Integerscanbespecifiedindecimal(base10),hexadecimal(base16),oroctal(base8)notation,optionally precededbyasign(or+). Touseoctalnotation,precedethenumberwitha0(zero).Tousehexadecimalnotationprecedethenumber with0x. Example#1Integerliterals <?php $a=1234;//decimalnumber $a=123;//anegativenumber $a=0123;//octalnumber(equivalentto83decimal) $a=0x1A;//hexadecimalnumber(equivalentto26decimal) ?> Formally,thestructureforintegerliteralsis:
decimal:[19][09]* |0 hexadecimal:0[xX][09afAF]+ octal:0[07]+ integer:[+]?decimal |[+]?hexadecimal |[+]?octal
Integeroverflow
IfPHPencountersanumberbeyondtheboundsoftheintegertype,itwillbeinterpretedasafloatinstead. Also,anoperationwhichresultsinanumberbeyondtheboundsoftheintegertypewillreturnafloatinstead. <?php $large_number=2147483647; var_dump($large_number); //output:int(2147483647) $large_number=2147483648; var_dump($large_number); //output:float(2147483648) //it'struealsoforhexadecimalspecifiedintegersbetween2^31and2^3 21: var_dump(0xffffffff); //output:float(4294967295) //thisdoesn'tgoforhexadecimalspecifiedintegersabove2^321: var_dump(0x100000000); //output:int(2147483647) $million=1000000; $large_number=50000*$million; var_dump($large_number); //output:float(50000000000) ?> Warning Unfortunately,therewasabuginPHPwhichcausedthistonotalwaysworkcorrectlywhennegative numberswereinvolved.Forexample,theresultof50000*$millionis429496728.However,whenboth operandswerepositive,therewasnoproblem. ThiswasfixedinPHP4.1.0. ThereisnointegerdivisionoperatorinPHP.1/2yieldsthefloat0.5.Thevaluecanbecastedtoanintegerto rounditdownwards,ortheround()functionprovidesfinercontroloverrounding. <?php var_dump(25/7);//float(3.5714285714286) var_dump((int)(25/7));//int(3) var_dump(round(25/7));//float(4) ?>
Convertingtointeger
Toexplicitlyconvertavaluetointeger,useeitherthe(int)or(integer)casts.However,inmostcasesthecast isnotneeded,sinceavaluewillbeautomaticallyconvertedifanoperator,functionorcontrolstructure requiresanintegerargument.Avaluecanalsobeconvertedtointegerwiththeintval()function. Seealso:typejuggling. Frombooleans FALSEwillyield0(zero),andTRUEwillyield1(one). Fromfloatingpointnumbers Whenconvertingfromfloattointeger,thenumberwillberoundedtowardszero. Ifthefloatisbeyondtheboundariesofinteger(usually+/2.15e+9=2^31),theresultisundefined,since thefloatdoesn'thaveenoughprecisiontogiveanexactintegerresult.Nowarning,notevenanoticewillbe issuedwhenthishappens! Warning Nevercastanunknownfractiontointeger,asthiscansometimesleadtounexpectedresults. <?php echo(int)((0.1+0.7)*10);//echoes7! ?> Seealsothewarningaboutfloatprecision. Fromstrings SeeStringconversiontonumbers Fromothertypes Caution Thebehaviourofconvertingtointegerisundefinedforothertypes.Donotrelyonanyobservedbehaviour, asitcanchangewithoutnotice.
Floatingpointnumbers
Floatingpointnumbers(alsoknownas"floats","doubles",or"realnumbers")canbespecifiedusinganyof thefollowingsyntaxes: <?php $a=1.234; $b=1.2e3; $c=7E10; ?> Formally: LNUM[09]+ DNUM([09]*[\.]{LNUM})|({LNUM}[\.][09]*) EXPONENT_DNUM[+]?(({LNUM}|{DNUM})[eE][+]?{LNUM}) Thesizeofafloatisplatformdependent,althoughamaximumof~1.8e308withaprecisionofroughly14 decimaldigitsisacommonvalue(the64bitIEEEformat). Warning
Floatingpointprecision
Itistypicalthatsimpledecimalfractionslike0.1or0.7cannotbeconvertedintotheirinternalbinary counterpartswithoutasmalllossofprecision.Thiscanleadtoconfusingresults:forexample, floor((0.1+0.7)*10)willusuallyreturn7insteadoftheexpected8,sincetheinternalrepresentationwillbe somethinglike7.9. Thisisduetothefactthatitisimpossibletoexpresssomefractionsindecimalnotationwithafinitenumber ofdigits.Forinstance,1/3indecimalformbecomes0.3. Sonevertrustfloatingnumberresultstothelastdigit,andnevercomparefloatingpointnumbersforequality. Ifhigherprecisionisnecessary,thearbitraryprecisionmathfunctionsandgmpfunctionsareavailable.
Convertingtofloat
Forinformationonconvertingstringstofloat,seeStringconversiontonumbers.Forvaluesofothertypes, theconversionisperformedbyconvertingthevaluetointegerfirstandthentofloat.SeeConvertingto integerformoreinformation.AsofPHP5,anoticeisthrownifanobjectisconvertedtofloat.
Strings
Astringisseriesofcharacters.BeforePHP6,acharacteristhesameasabyte.Thatis,thereareexactly256 differentcharacterspossible.ThisalsoimpliesthatPHPhasnonativesupportofUnicode.Seeutf8_encode() andutf8_decode()forsomebasicUnicodefunctionality. Note:Itisnoproblemforastringtobecomeverylarge.PHPimposesnoboundaryonthesizeof astring;theonlylimitistheavailablememoryofthecomputeronwhichPHPisrunning.
Syntax
Astringliteralcanbespecifiedinfourdifferentways:
Singlequoted Thesimplestwaytospecifyastringistoencloseitinsinglequotes(thecharacter'). Tospecifyaliteralsinglequote,escapeitwithabackslash(\).Tospecifyaliteralbackslashbeforeasingle quote,orattheendofthestring,doubleit(\\).Notethatattemptingtoescapeanyothercharacterwillprint thebackslashtoo. Note:Unlikethetwoothersyntaxes,variablesandescapesequencesforspecialcharacterswill notbeexpandedwhentheyoccurinsinglequotedstrings. <?php echo'thisisasimplestring'; echo'Youcanalsohaveembeddednewlinesin stringsthiswayasitis okaytodo'; //Outputs:Arnoldoncesaid:"I'llbeback" echo'Arnoldoncesaid:"I\'llbeback"'; //Outputs:YoudeletedC:\*.*? echo'YoudeletedC:\\*.*?'; //Outputs:YoudeletedC:\*.*? echo'YoudeletedC:\*.*?'; //Outputs:Thiswillnotexpand:\nanewline echo'Thiswillnotexpand:\nanewline'; //Outputs:Variablesdonot$expand$either echo'Variablesdonot$expand$either';
?> Doublequoted Ifthestringisenclosedindoublequotes("),PHPwillinterpretmoreescapesequencesforspecial characters: Escapedcharacters Sequence \n \r \t \v \f \\ \$ \" \[07]{1,3} linefeed(LFor0x0A(10)inASCII) carriagereturn(CRor0x0D(13)inASCII) horizontaltab(HTor0x09(9)inASCII) verticaltab(VTor0x0B(11)inASCII)(sincePHP5.2.5) formfeed(FFor0x0C(12)inASCII)(sincePHP5.2.5) backslash dollarsign doublequote thesequenceofcharactersmatchingtheregularexpressionisacharacterinoctal notation thesequenceofcharactersmatchingtheregularexpressionisacharacterinhexadecimal notation Meaning
\x[09AFaf]{1,2}
muststartwithanondigitcharacterorunderscore. Warning Itisveryimportanttonotethatthelinewiththeclosingidentifiermustcontainnoothercharacters,except possiblyasemicolon(;).Thatmeansespeciallythattheidentifiermaynotbeindented,andtheremaynotbe anyspacesortabsbeforeorafterthesemicolon.It'salsoimportanttorealizethatthefirstcharacterbefore theclosingidentifiermustbeanewlineasdefinedbythelocaloperatingsystem.Thisis\nonUNIX systems,includingMacOSX.Theclosingdelimiter(possiblyfollowedbyasemicolon)mustalsobe followedbyanewline. Ifthisruleisbrokenandtheclosingidentifierisnot"clean",itwillnotbeconsideredaclosingidentifier,and PHPwillcontinuelookingforone.Ifaproperclosingidentifierisnotfoundbeforetheendofthecurrent file,aparseerrorwillresultatthelastline. Heredocscannotbeusedforinitializingclassmembers.Usenowdocsinstead. Example#1Invalidexample <?php classfoo{ public$bar=<<<EOT bar EOT; } ?> Heredoctextbehavesjustlikeadoublequotedstring,withoutthedoublequotes.Thismeansthatquotesina heredocdonotneedtobeescaped,buttheescapecodeslistedabovecanstillbeused.Variablesare expanded,butthesamecaremustbetakenwhenexpressingcomplexvariablesinsideaheredocaswith strings. Example#2Heredocstringquotingexample <?php $str=<<<EOD Exampleofstring spanningmultiplelines usingheredocsyntax. EOD; /*Morecomplexexample,withvariables.*/ classfoo { var$foo; var$bar; functionfoo() { $this>foo='Foo'; $this>bar=array('Bar1','Bar2','Bar3'); } }
ItsalsopossibletousetheHeredocsyntaxtopassdatatofunctionarguments: Example#3Heredocinargumentsexample <?php var_dump(array(<<<EOD foobar! EOD )); ?> Note:HeredocsupportwasaddedinPHP4. Nowdoc Nowdocsaretosinglequotedstringswhatheredocsaretodoublequotedstrings.Anowdocisspecified similarlytoaheredoc,butnoparsingisdoneinsideanowdoc.TheconstructisidealforembeddingPHP codeorotherlargeblocksoftextwithouttheneedforescaping.Itsharessomefeaturesincommonwiththe SGML<![CDATA[]]>construct,inthatitdeclaresablockoftextwhichisnotforparsing. Anowdocisidentifiedwiththesame<<<seqeuenceusedforheredocs,buttheidentifierwhichfollowsis enclosedinsinglequotes,e.g.<<<'EOT'.Alltherulesforheredocidentifiersalsoapplytonowdoc identifiers,especiallythoseregardingtheappearanceoftheclosingidentifier. Example#4Nowdocstringquotingexample <?php $str=<<<'EOD' Exampleofstring spanningmultiplelines usingnowdocsyntax. EOD; /*Morecomplexexample,withvariables.*/ classfoo {
public$foo; public$bar; functionfoo() { $this>foo='Foo'; $this>bar=array('Bar1','Bar2','Bar3'); } } $foo=newfoo(); $name='MyName'; echo<<<'EOT' Mynameis"$name".Iamprintingsome$foo>foo. Now,Iamprintingsome{$foo>bar[1]}. Thisshouldnotprintacapital'A':x41 EOT; ?> Theaboveexamplewilloutput:
Mynameis"$name".Iamprintingsome$foo>foo. Now,Iamprintingsome{$foo>bar[1]}. Thisshouldnotprintacapital'A':\x41
Note:Unlikeheredocs,nowdocscanbeusedinanystaticdatacontext.Thetypicalexampleis initializingclassmembersorconstants: Example#5Staticdataexample <?php classfoo{ public$bar=<<<'EOT' bar EOT; } ?> Note:NowdocsupportwasaddedinPHP5.3.0. Variableparsing Whenastringisspecifiedindoublequotesorwithheredoc,variablesareparsedwithinit. Therearetwotypesofsyntax:asimpleoneandacomplexone.Thesimplesyntaxisthemostcommonand convenient.Itprovidesawaytoembedavariable,anarrayvalue,oranobjectpropertyinastringwitha minimumofeffort. ThecomplexsyntaxwasintroducedinPHP4,andcanberecognisedbythecurlybracessurroundingthe expression.
Simplesyntax
Ifadollarsign($)isencountered,theparserwillgreedilytakeasmanytokensaspossibletoformavalid variablename.Enclosethevariablenameincurlybracestoexplicitlyspecifytheendofthename. <?php $beer='Heineken'; echo"$beer'stasteisgreat";//works;"'"isaninvalidcharacterfor variablenames echo"Hedranksome$beers";//won'twork;'s'isavalidcharacterfo rvariablenamesbutthevariableis"$beer" echo"Hedranksome${beer}s";//works echo"Hedranksome{$beer}s";//works ?> Similarly,anarrayindexoranobjectpropertycanbeparsed.Witharrayindices,theclosingsquarebracket (])markstheendoftheindex.Thesamerulesapplytoobjectpropertiesastosimplevariables. <?php //Theseexamplesarespecifictousingarraysinsideofstrings. //Whenoutsideofastring,alwaysquotearraystringkeysanddonotus e //{braces}. //Showallerrors error_reporting(E_ALL); $fruits=array('strawberry'=>'red','banana'=>'yellow'); //Works,butnotethatthisworksdifferentlyoutsideastring echo"Abananais$fruits[banana]."; //Works echo"Abananais{$fruits['banana']}."; //Works,butPHPlooksforaconstantnamedbananafirst,asdescribedb elow. echo"Abananais{$fruits[banana]}."; //Won'twork,usebraces.Thisresultsinaparseerror. echo"Abananais$fruits['banana']."; //Works echo"Abananais".$fruits['banana']."."; //Works echo"Thissquareis$square>widthmetersbroad."; //Won'twork.Forasolution,seethecomplexsyntax. echo"Thissquareis$square>width00centimetersbroad."; ?> Foranythingmorecomplex,youshouldusethecomplexsyntax.
Complex(curly)syntax
Thisisn'tcalledcomplexbecausethesyntaxiscomplex,butbecauseitallowsfortheuseofcomplex expressions. Infact,anyvalueinthenamespacecanbeincludedinastringwiththissyntax.Simplywritetheexpression thesamewayasitwouldappearedoutsidethestring,andthenwrapitin{and}.Since{cannotbeescaped, thissyntaxwillonlyberecognisedwhenthe$immediatelyfollowsthe{.Use{\$togetaliteral{$.Some examplestomakeitclear: <?php //Showallerrors error_reporting(E_ALL); $great='fantastic'; //Won'twork,outputs:Thisis{fantastic} echo"Thisis{$great}"; //Works,outputs:Thisisfantastic echo"Thisis{$great}"; echo"Thisis${great}"; //Works echo"Thissquareis{$square>width}00centimetersbroad."; //Works echo"Thisworks:{$arr[4][3]}"; //Thisiswrongforthesamereasonas$foo[bar]iswrongoutsideastr ing. //Inotherwords,itwillstillwork,butonlybecausePHPfirstlooksf ora //constantnamedfoo;anerroroflevelE_NOTICE(undefinedconstant)wi llbe //thrown. echo"Thisiswrong:{$arr[foo][3]}"; //Works.Whenusingmultidimensionalarrays,alwaysusebracesarounda rrays //wheninsideofstrings echo"Thisworks:{$arr['foo'][3]}"; //Works. echo"Thisworks:".$arr['foo'][3]; echo"Thisworkstoo:{$obj>values[3]>name}"; echo"Thisisthevalueofthevarnamed$name:{${$name}}"; echo"ThisisthevalueofthevarnamedbythereturnvalueofgetName() :{${getName()}}"; echo"Thisisthevalueofthevarnamedbythereturnvalueof\$object >getName():{${$object>getName()}}";
?> Note:Functionsandmethodcallsinside{$}worksincePHP5. Stringaccessandmodificationbycharacter Characterswithinstringsmaybeaccessedandmodifiedbyspecifyingthezerobasedoffsetofthedesired characterafterthestringusingsquarearraybrackets,asin$str[42].Thinkofastringasanarrayof charactersforthispurpose. Note:Stringsmayalsobeaccessedusingbraces,asin$str{42},forthesamepurpose.However, thissyntaxisdeprecatedasofPHP6.Usesquarebracketsinstead. Example#6Somestringexamples <?php //Getthefirstcharacterofastring $str='Thisisatest.'; $first=$str[0]; //Getthethirdcharacterofastring $third=$str[2]; //Getthelastcharacterofastring. $str='Thisisstillatest.'; $last=$str[strlen($str)1]; //Modifythelastcharacterofastring $str='Lookatthesea'; $str[strlen($str)1]='e'; ?> Note:Accessingvariablesofothertypesusing[]or{}silentlyreturnsNULL.
Usefulfunctionsandoperators
Stringsmaybeconcatenatedusingthe'.'(dot)operator.Notethatthe'+'(addition)operatorwillnotworkfor this.SeeStringoperatorsformoreinformation. Thereareanumberofusefulfunctionsforstringmanipulation. Seethestringfunctionssectionforgeneralfunctions,andtheregularexpressionfunctionsorthePerl compatibleregularexpressionfunctionsforadvancedfind&replacefunctionality. TherearealsofunctionsforURLstrings,andfunctionstoencrypt/decryptstrings(mcryptandmhash). Finally,seealsothecharactertypefunctions.
Convertingtostring
Avaluecanbeconvertedtoastringusingthe(string)castorthestrval()function.Stringconversionis automaticallydoneinthescopeofanexpressionwhereastringisneeded.Thishappenswhenusingthe echo()orprint()functions,orwhenavariableiscomparedtoastring.ThesectionsonTypesandType Jugglingwillmakethefollowingclearer.Seealsothesettype()function. AbooleanTRUEvalueisconvertedtothestring"1".BooleanFALSEisconvertedto""(theemptystring). Thisallowsconversionbackandforthbetweenbooleanandstringvalues. Anintegerorfloatisconvertedtoastringrepresentingthenumbertextually(includingtheexponentpartfor floats).Floatingpointnumberscanbeconvertedusingexponentialnotation(4.1E+6). Note:Thedecimalpointcharacterisdefinedinthescript'slocale(categoryLC_NUMERIC).See thesetlocale()function. Arraysarealwaysconvertedtothestring"Array";becauseofthis,echo()andprint()cannotbythemselves showthecontentsofanarray.Toviewasingleelement,useaconstructionsuchasecho$arr['foo'].See belowfortipsonviewingtheentirecontents. ObjectsinPHP4arealwaysconvertedtothestring"Object".Toprintthevaluesofobjectmembersfor debuggingreasons,readtheparagraphsbelow.Togetanobject'sclassname,usetheget_class()function.As ofPHP5,the__toStringmethodisusedwhenapplicable. Resourcesarealwaysconvertedtostringswiththestructure"Resourceid#1",where1istheuniquenumber assignedtotheresourcebyPHPatruntime.Donotrelyuponthisstructure;itissubjecttochange.Togeta resource'stype,usetheget_resource_type()function. NULLisalwaysconvertedtoanemptystring. Asstatedabove,directlyconvertinganarray,object,orresourcetoastringdoesnotprovideanyuseful informationaboutthevaluebeyonditstype.Seethefunctionsprint_r()andvar_dump()formoreeffective meansofinspectingthecontentsofthesetypes. MostPHPvaluescanalsobeconvertedtostringsforpermanentstorage.Thismethodiscalledserialization, andisperformedbytheserialize()function.IfthePHPenginewasbuiltwithWDDXsupport,PHPvalues canalsobeserializedaswellformedXMLtext.
Stringconversiontonumbers
Whenastringisevaluatedinanumericcontext,theresultingvalueandtypearedeterminedasfollows. Thestringwillbeevaluatedasafloatifitcontainsanyofthecharacters'.','e',or'E'.Otherwise,itwillbe evaluatedasaninteger. Thevalueisgivenbytheinitialportionofthestring.Ifthestringstartswithvalidnumericdata,thiswillbe thevalueused.Otherwise,thevaluewillbe0(zero).Validnumericdataisanoptionalsign,followedbyone ormoredigits(optionallycontainingadecimalpoint),followedbyanoptionalexponent.Theexponentisan 'e'or'E'followedbyoneormoredigits.
<?php $foo=1+"10.5";//$fooisfloat(11.5) $foo=1+"1.3e3";//$fooisfloat(1299) $foo=1+"bob1.3e3";//$fooisinteger(1) $foo=1+"bob3";//$fooisinteger(1) $foo=1+"10SmallPigs";//$fooisinteger(11) $foo=4+"10.2LittlePiggies";//$fooisfloat(14.2) $foo="10.0pigs"+1;//$fooisfloat(11) $foo="10.0pigs"+1.0;//$fooisfloat(11) ?> Formoreinformationonthisconversion,seetheUnixmanualpageforstrtod(3). Totestanyoftheexamplesinthissection,cutandpastetheexamplesandinsertthefollowinglinetosee what'sgoingon: <?php echo"\$foo==$foo;typeis".gettype($foo)."<br/>\n"; ?> Donotexpecttogetthecodeofonecharacterbyconvertingittointeger,asisdoneinC.Usetheord()and chr()functionstoconvertbetweenASCIIcodesandcharacters.
Arrays
AnarrayinPHPisactuallyanorderedmap.Amapisatypethatassociatesvaluestokeys.Thistypeis optimizedforseveraldifferentuses;itcanbetreatedasanarray,list(vector),hashtable(animplementation ofamap),dictionary,collection,stack,queue,andprobablymore.Asarrayvaluescanbeotherarrays,trees andmultidimensionalarraysarealsopossible. Explanationofthosedatastructuresisbeyondthescopeofthismanual,butatleastoneexampleisprovided foreachofthem.Formoreinformation,looktowardstheconsiderableliteraturethatexistsaboutthisbroad topic.
Syntax
Specifyingwitharray() Anarraycanbecreatedbythearray()languageconstruct.Ittakesasparametersanynumberofcomma separatedkey=>valuepairs.
array(key=>value ,... ) //keymayonlybeanintegerorstring //valuemaybeanyvalueofanytype
<?php $arr=array("foo"=>"bar",12=>true); echo$arr["foo"];//bar echo$arr[12];//1 ?> Akeymaybeeitheranintegerorastring.Ifakeyisthestandardrepresentationofaninteger,itwillbe interpretedassuch(i.e."8"willbeinterpretedas8,while"08"willbeinterpretedas"08").Floatsinkeyare truncatedtointeger.TheindexedandassociativearraytypesarethesametypeinPHP,whichcanboth containintegerandstringindices. AvaluecanbeanyPHPtype. <?php $arr=array("somearray"=>array(6=>5,13=>9,"a"=>42)); echo$arr["somearray"][6];//5 echo$arr["somearray"][13];//9 echo$arr["somearray"]["a"];//42 ?> Ifakeyisnotspecifiedforavalue,themaximumoftheintegerindicesistakenandthenewkeywillbethat valueplus1.Ifakeythatalreadyhasanassignedvalueisspecified,thatvaluewillbeoverwritten. <?php //Thisarrayisthesameas... array(5=>43,32,56,"b"=>12); //...thisarray array(5=>43,6=>32,7=>56,"b"=>12); ?> Warning BeforePHP4.3.0,appendingtoanarrayinwhichthecurrentmaximumkeywasnegativewouldcreatea newkeyasdescribedabove.SincePHP4.3.0,thenewkeywillbe0. UsingTRUEaskeywillevaluatetointeger1asakey.UsingFALSEaskeywillevaluatetointeger0asa key.UsingNULLasakeywillevaluatetotheemptystring.Usingtheemptystringasakeywillcreate(or overwrite)akeywiththeemptystringanditsvalue;itisnotthesameasusingemptybrackets. Arraysandobjectscannotbeusedaskeys.Doingsowillresultinawarning:Illegaloffsettype. Creating/modifyingwithsquarebracketsyntax Anexistingarraycanbemodifiedbyexplicitlysettingvaluesinit. Thisisdonebyassigningvaluestothearray,specifyingthekeyinbrackets.Thekeycanalsobeomitted, resultinginanemptypairofbrackets([]).
$arr[key]=value; $arr[]=value;
//keymaybeanintegerorstring //valuemaybeanyvalueofanytype
If$arrdoesn'texistyet,itwillbecreated,sothisisalsoanalternativewaytocreateanarray.Tochangea certainvalue,assignanewvaluetothatelementusingitskey.Toremoveakey/valuepair,calltheunset() functiononit. <?php $arr=array(5=>1,12=>2); $arr[]=56;//Thisisthesameas$arr[13]=56; //atthispointofthescript $arr["x"]=42;//Thisaddsanewelementto //thearraywithkey"x" unset($arr[5]);//Thisremovestheelementfromthearray unset($arr);//Thisdeletesthewholearray ?> Note:Asmentionedabove,ifnokeyisspecified,themaximumoftheexistingintegerindicesis taken,andthenewkeywillbethatmaximumvalueplus1.Ifnointegerindicesexistyet,thekey willbe0(zero).Ifakeythatalreadyhasavalueisspecified,thatvaluewillbeoverwritten. Notethatthemaximumintegerkeyusedforthisneednotcurrentlyexistinthearray.Itneed onlyhaveexistedinthearrayatsometimesincethelasttimethearraywasreindexed.The followingexampleillustrates: <?php //Createasimplearray. $array=array(1,2,3,4,5); print_r($array); //Nowdeleteeveryitem,butleavethearrayitselfintact: foreach($arrayas$i=>$value){ unset($array[$i]); } print_r($array); //Appendanitem(notethatthenewkeyis5,insteadof0). $array[]=6; print_r($array); //Reindex: $array=array_values($array); $array[]=7; print_r($array); ?> Theaboveexamplewilloutput:
Array ( [0]=>1 [1]=>2 [2]=>3
Usefulfunctions
Therearequiteafewusefulfunctionsforworkingwitharrays.Seethearrayfunctionssection. Note:Theunset()functionallowsremovingkeysfromanarray.Beawarethatthearraywillnot bereindexed.Ifatrue"removeandshift"behaviorisdesired,thearraycanbereindexedusing thearray_values()function. <?php $a=array(1=>'one',2=>'two',3=>'three'); unset($a[2]); /*willproduceanarraythatwouldhavebeendefinedas $a=array(1=>'one',3=>'three'); andNOT $a=array(1=>'one',2=>'three'); */ $b=array_values($a); //Now$bisarray(0=>'one',1=>'three') ?> Theforeachcontrolstructureexistsspecificallyforarrays.Itprovidesaneasywaytotraverseanarray.
Arraydo'sanddon'ts
Whyis$foo[bar]wrong? Alwaysusequotesaroundastringliteralarrayindex.Forexample,$foo['bar']iscorrect,while$foo[bar]is not.Butwhy?Itiscommontoencounterthiskindofsyntaxinoldscripts: <?php $foo[bar]='enemy'; echo$foo[bar]; //etc ?> Thisiswrong,butitworks.Thereasonisthatthiscodehasanundefinedconstant(bar)ratherthanastring ('bar'noticethequotes).PHPmayinfuturedefineconstantswhich,unfortunatelyforsuchcode,havethe
samename.ItworksbecausePHPautomaticallyconvertsabarestring(anunquotedstringwhichdoesnot correspondtoanyknownsymbol)intoastringwhichcontainsthebarestring.Forinstance,ifthereisno definedconstantnamedbar,thenPHPwillsubstituteinthestring'bar'andusethat. Note:Thisdoesnotmeantoalwaysquotethekey.Donotquotekeyswhichareconstantsor variables,asthiswillpreventPHPfrominterpretingthem. <?php error_reporting(E_ALL); ini_set('display_errors',true); ini_set('html_errors',false); //Simplearray: $array=array(1,2); $count=count($array); for($i=0;$i<$count;$i++){ echo"\nChecking$i:\n"; echo"Bad:".$array['$i']."\n"; echo"Good:".$array[$i]."\n"; echo"Bad:{$array['$i']}\n"; echo"Good:{$array[$i]}\n"; } ?> Theaboveexamplewilloutput:
Checking0: Notice:Undefinedindex:$iin/path/to/script.htmlonline9 Bad: Good:1 Notice:Undefinedindex:$iin/path/to/script.htmlonline11 Bad: Good:1 Checking1: Notice:Undefinedindex:$iin/path/to/script.htmlonline9 Bad: Good:2 Notice:Undefinedindex:$iin/path/to/script.htmlonline11 Bad: Good:2
Moreexamplestodemonstratethisbehaviour: <?php //Showallerrors error_reporting(E_ALL); $arr=array('fruit'=>'apple','veggie'=>'carrot'); //Correct print$arr['fruit'];//apple print$arr['veggie'];//carrot //Incorrect.ThisworksbutalsothrowsaPHPerroroflevelE_NOTICEb ecause //ofanundefinedconstantnamedfruit // //Notice:Useofundefinedconstantfruitassumed'fruit'in... print$arr[fruit];//apple
//Thisdefinesaconstanttodemonstratewhat'sgoingon.Thevalue've ggie' //isassignedtoaconstantnamedfruit. define('fruit','veggie'); //Noticethedifferencenow print$arr['fruit'];//apple print$arr[fruit];//carrot //Thefollowingisokay,asit'sinsideastring.Constantsarenotlook edfor //withinstrings,sonoE_NOTICEoccurshere print"Hello$arr[fruit]";//Helloapple //Withoneexception:bracessurroundingarrayswithinstringsallowsco nstants //tobeinterpreted print"Hello{$arr[fruit]}";//Hellocarrot print"Hello{$arr['fruit']}";//Helloapple //Thiswillnotwork,andwillresultinaparseerror,suchas: //Parseerror:parseerror,expectingT_STRING'orT_VARIABLE'orT_NUM_ STRING' //Thisofcourseappliestousingsuperglobalsinstringsaswell print"Hello$arr['fruit']"; print"Hello$_GET['foo']"; //Concatenationisanotheroption print"Hello".$arr['fruit'];//Helloapple ?> Whenerror_reportingissettoshowE_NOTICElevelerrors(bysettingittoE_ALL,forexample),suchuses willbecomeimmediatelyvisible.Bydefault,error_reportingissetnottoshownotices. Asstatedinthesyntaxsection,what'sinsidethesquarebrackets('['and']')mustbeanexpression.This meansthatcodelikethisworks: <?php echo$arr[somefunc($bar)]; ?> Thisisanexampleofusingafunctionreturnvalueasthearrayindex.PHPalsoknowsaboutconstants: <?php $error_descriptions[E_ERROR]="Afatalerrorhasoccured"; $error_descriptions[E_WARNING]="PHPissuedawarning"; $error_descriptions[E_NOTICE]="Thisisjustaninformalnotice"; ?> NotethatE_ERRORisalsoavalididentifier,justlikebarinthefirstexample.Butthelastexampleisinfact thesameaswriting: <?php
Convertingtoarray
Foranyofthetypes:integer,float,string,booleanandresource,convertingavaluetoanarrayresultsinan arraywithasingleelementwithindexzeroandthevalueofthescalarwhichwasconverted.Inotherwords, (array)$scalarValueisexactlythesameasarray($scalarValue). Ifanobjectisconvertedtoanarray,theresultisanarraywhoseelementsaretheobject'sproperties.The keysarethemembervariablenames,withafewnotableexceptions:privatevariableshavetheclassname prependedtothevariablename;protectedvariableshavea'*'prependedtothevariablename.These prependedvalueshavenullbytesoneitherside.Thiscanresultinsomeunexpectedbehaviour: <?php classA{ private$A;//Thiswillbecome'\0A\0A' } classBextendsA{ private$A;//Thiswillbecome'\0B\0A' public$AA;//Thiswillbecome'AA' } var_dump((array)newB()); ?> Theabovewillappeartohavetwokeysnamed'AA',althoughoneofthemisactuallynamed'\0A\0A'. ConvertingNULLtoanarrayresultsinanemptyarray.
Comparing
Itispossibletocomparearrayswiththearray_diff()functionandwitharrayoperators.
Examples
ThearraytypeinPHPisveryversatile.Herearesomeexamples: <?php //this $a=array('color'=>'red', 'taste'=>'sweet', 'shape'=>'round', 'name'=>'apple', 4//keywillbe0 ); //iscompletelyequivalentwith $a['color']='red'; $a['taste']='sweet'; $a['shape']='round'; $a['name']='apple'; $a[]=4;//keywillbe0 $b[]='a'; $b[]='b'; $b[]='c'; //willresultinthearrayarray(0=>'a',1=>'b',2=>'c'), //orsimplyarray('a','b','c') ?> Example#1Usingarray() <?php //Arrayas(property)map $map=array('version'=>4, 'OS'=>'Linux', 'lang'=>'english', 'short_tags'=>true ); //strictlynumericalkeys $array=array(7, 8, 0, 156, 10 ); //thisisthesameasarray(0=>7,1=>8,...) $switching=array(10,//key=0 5=>6, 3=>7, 'a'=>4, 11,//key=6(maximumofintegerindiceswa s5) '8'=>2,//key=8(integer!) '02'=>77,//key='02'
0=>12//thevalue10willbeoverwrittenby12 ); //emptyarray $empty=array(); ?> Example#2Collection <?php $colors=array('red','blue','green','yellow'); foreach($colorsas$color){ echo"Doyoulike$color?\n"; } ?> Theaboveexamplewilloutput:
Doyoulikered? Doyoulikeblue? Doyoulikegreen? Doyoulikeyellow?
ChangingthevaluesofthearraydirectlyispossiblesincePHP5bypassingthembyreference.Beforethat,a workaroundisnecessary: Example#3Collection <?php //PHP5 foreach($colorsas&$color){ $color=strtoupper($color); } unset($color);/*ensurethatfollowingwritesto $colorwillnotmodifythelastarrayelement*/ //Workaroundforolderversions foreach($colorsas$key=>$color){ $colors[$key]=strtoupper($color); } print_r($colors); ?> Theaboveexamplewilloutput:
Array ( [0]=>RED [1]=>BLUE [2]=>GREEN [3]=>YELLOW )
Thisexamplecreatesaonebasedarray.
Example#5Fillinganarray <?php //fillanarraywithallitemsfromadirectory $handle=opendir('.'); while(false!==($file=readdir($handle))){ $files[]=$file; } closedir($handle); ?> Arraysareordered.Theordercanbechangedusingvarioussortingfunctions.Seethearrayfunctionssection formoreinformation.Thecount()functioncanbeusedtocountthenumberofitemsinanarray. Example#6Sortinganarray <?php sort($files); print_r($files); ?> Becausethevalueofanarraycanbeanything,itcanalsobeanotherarray.Thisenablesthecreationof recursiveandmultidimensionalarrays. Example#7Recursiveandmultidimensionalarrays <?php $fruits=array("fruits"=>array("a"=>"orange", "b"=>"banana", "c"=>"apple" ), "numbers"=>array(1, 2, 3, 4, 5, 6 ),
"holes"=>array("first", 5=>"second", "third" ) ); //Someexamplestoaddressvaluesinthearrayabove echo$fruits["holes"][5];//prints"second" echo$fruits["fruits"]["a"];//prints"orange" unset($fruits["holes"][0]);//remove"first" //Createanewmultidimensionalarray $juices["apple"]["green"]="good"; ?> Arrayassignmentalwaysinvolvesvaluecopying.Italsomeansthattheinternalarraypointerusedby current()andsimilarfunctionsisreset.Usethereferenceoperatortocopyanarraybyreference. <?php $arr1=array(2,3); $arr2=$arr1; $arr2[]=4;//$arr2ischanged, //$arr1isstillarray(2,3) $arr3=&$arr1; $arr3[]=4;//now$arr1and$arr3arethesame ?>
Objects
ObjectInitialization
Tocreateanewobject,usethenewstatementtoinstantiateaclass: <?php classfoo { functiondo_foo() { echo"Doingfoo."; } } $bar=newfoo; $bar>do_foo(); ?> Forafulldiscussion,seetheClassesandObjectschapter.
Convertingtoobject
Ifanobjectisconvertedtoanobject,itisnotmodified.Ifavalueofanyothertypeisconvertedtoanobject, anewinstanceofthestdClassbuiltinclassiscreated.IfthevaluewasNULL,thenewinstancewillbe empty.Arraysconverttoanobjectwithpropertiesnamedbykeys,andcorrespondingvalues.Foranyother value,amembervariablenamedscalarwillcontainthevalue. <?php $obj=(object)'ciao'; echo$obj>scalar;//outputs'ciao' ?>
Resources
Aresourceisaspecialvariable,holdingareferencetoanexternalresource.Resourcesarecreatedandused byspecialfunctions.Seetheappendixforalistingofallthesefunctionsandthecorrespondingresource types. Note:TheresourcetypewasintroducedinPHP4 Seealsotheget_resource_type()function.
Convertingtoresource
Asresourcevariablesholdspecialhandlerstoopenedfiles,databaseconnections,imagecanvasareasandthe like,convertingtoaresourcemakesnosense.
Freeingresources
ThankstothereferencecountingsystemintroducedwithPHP4'sZendEngine,aresourcewithnomore referencestoitisdetectedautomatically,anditisfreedbythegarbagecollector.Forthisreason,itisrarely necessarytofreethememorymanually. Note:Persistentdatabaselinksareanexceptiontothisrule.Theyarenotdestroyedbythe garbagecollector.Seethepersistentconnectionssectionformoreinformation.
NULL
ThespecialNULLvaluerepresentsavariablewithnovalue.NULListheonlypossiblevalueoftypeNULL.
Note:ThenulltypewasintroducedinPHP4. Avariableisconsideredtobenullif:
Syntax
Thereisonlyonevalueoftypenull,andthatisthecaseinsensitivekeywordNULL. <?php $var=NULL; ?> Seealsothefunctionsis_null()andunset().
CastingtoNULL
Castingavariabletonullwillremovethevariableandunsetitsvalue.
Pseudotypesandvariablesusedinthisdocumentation
mixed
mixedindicatesthataparametermayacceptmultiple(butnotnecessarilyall)types. gettype()forexamplewillacceptallPHPtypes,whilestr_replace()willacceptstringsandarrays.
number
numberindicatesthataparametercanbeeitherintegerorfloat.
callback
Somefunctionslikecall_user_func()orusort()acceptuserdefinedcallbackfunctionsasaparameter. Callbackfunctionscannotonlybesimplefunctions,butalsoobjectmethods,includingstaticclassmethods.
APHPfunctionispassedbyitsnameasastring.Anybuiltinoruserdefinedfunctioncanbeused,except languageconstructssuchas:array(),echo(),empty(),eval(),exit(),isset(),list(),print()orunset(). Amethodofaninstantiatedobjectispassedasanarraycontaininganobjectatindex0andthemethodname atindex1. Staticclassmethodscanalsobepassedwithoutinstantiatinganobjectofthatclassbypassingtheclassname insteadofanobjectatindex0. Apartfromcommonuserdefinedfunction,create_function()canalsobeusedtocreateananonymous callbackfunction. Example#1Callbackfunctionexamples <?php //Anexamplecallbackfunction functionmy_callback_function(){ echo'helloworld!'; } //Anexamplecallbackmethod classMyClass{ staticfunctionmyCallbackMethod(){ echo'HelloWorld!'; } } //Type1:Simplecallback call_user_func('my_callback_function'); //Type2:Staticclassmethodcall call_user_func(array('MyClass','myCallbackMethod')); //Type3:Objectmethodcall $obj=newMyClass(); call_user_func(array($obj,'myCallbackMethod')); //Type4:Staticclassmethodcall(AsofPHP5.2.3) call_user_func('MyClass::myCallbackMethod'); //Type5:Relativestaticclassmethodcall(AsofPHP5.3.0) classA{ publicstaticfunctionwho(){ echo"A\n"; } } classBextendsA{ publicstaticfunctionwho(){ echo"B\n"; } }
void
voidasareturntypemeansthatthereturnvalueisuseless.voidinaparameterlistmeansthatthefunction doesn'tacceptanyparameters.
...
$...infunctionprototypesmeansandsoon.Thisvariablenameisusedwhenafunctioncantakean endlessnumberofarguments.
TypeJuggling
PHPdoesnotrequire(orsupport)explicittypedefinitioninvariabledeclaration;avariable'stypeis determinedbythecontextinwhichthevariableisused.Thatistosay,ifastringvalueisassignedtovariable $var,$varbecomesastring.Ifanintegervalueisthenassignedto$var,itbecomesaninteger. AnexampleofPHP'sautomatictypeconversionistheadditionoperator'+'.Ifeitheroperandisafloat,then bothoperandsareevaluatedasfloats,andtheresultwillbeafloat.Otherwise,theoperandswillbe interpretedasintegers,andtheresultwillalsobeaninteger.Notethatthisdoesnotchangethetypesofthe operandsthemselves;theonlychangeisinhowtheoperandsareevaluatedandwhatthetypeofthe expressionitselfis. <?php $foo="0";//$fooisstring(ASCII48) $foo+=2;//$fooisnowaninteger(2) $foo=$foo+1.3;//$fooisnowafloat(3.3) $foo=5+"10LittlePiggies";//$fooisinteger(15) $foo=5+"10SmallPigs";//$fooisinteger(15) ?> Ifthelasttwoexamplesaboveseemodd,seeStringconversiontonumbers. Toforceavariabletobeevaluatedasacertaintype,seethesectiononTypecasting.Tochangethetypeofa variable,seethesettype()function. Totestanyoftheexamplesinthissection,usethevar_dump()function. Note:Thebehaviourofanautomaticconversiontoarrayiscurrentlyundefined. Also,becausePHPsupportsindexingintostringsviaoffsetsusingthesamesyntaxasarray
TypeCasting
TypecastinginPHPworksmuchasitdoesinC:thenameofthedesiredtypeiswritteninparenthesesbefore thevariablewhichistobecast. <?php $foo=10;//$fooisaninteger $bar=(boolean)$foo;//$barisaboolean ?> Thecastsallowedare:
(binary)castingandbprefixforwardsupportwasaddedinPHP5.2.1 Notethattabsandspacesareallowedinsidetheparentheses,sothefollowingarefunctionallyequivalent: <?php $foo=(int)$bar; $foo=(int)$bar; ?> Castingliteralstringsandvariablestobinarystrings: <?php $binary=(binary)$string; $binary=b"binarystring"; ?> Note:Insteadofcastingavariabletoastring,itisalsopossibletoenclosethevariableindouble quotes. <?php $foo=10;//$fooisaninteger $str="$foo";//$strisastring $fst=(string)$foo;//$fstisalsoastring
Variables
TableofContents
Basics
VariablesinPHParerepresentedbyadollarsignfollowedbythenameofthevariable.Thevariablenameis casesensitive. VariablenamesfollowthesamerulesasotherlabelsinPHP.Avalidvariablenamestartswithaletteror underscore,followedbyanynumberofletters,numbers,orunderscores.Asaregularexpression,itwouldbe expressedthus:'[azAZ_\x7f\xff][azAZ09_\x7f\xff]*' Note:Forourpurposeshere,aletterisaz,AZ,andtheASCIIcharactersfrom127through255 (0x7f0xff). Note:$thisisaspecialvariablethatcan'tbeassigned.
Tip SeealsotheUserlandNamingGuide. Forinformationonvariablerelatedfunctions,seetheVariableFunctionsReference. <?php $var='Bob'; $Var='Joe'; echo"$var,$Var";//outputs"Bob,Joe" $4site='notyet';//invalid;startswithanumber $_4site='notyet';//valid;startswithanunderscore $tyte='mansikka';//valid;''is(Extended)ASCII228. ?> Bydefault,variablesarealwaysassignedbyvalue.Thatistosay,whenyouassignanexpressiontoa variable,theentirevalueoftheoriginalexpressioniscopiedintothedestinationvariable.Thismeans,for instance,thatafterassigningonevariable'svaluetoanother,changingoneofthosevariableswillhaveno effectontheother.Formoreinformationonthiskindofassignment,seethechapteronExpressions. PHPalsooffersanotherwaytoassignvaluestovariables:assignbyreference.Thismeansthatthenew variablesimplyreferences(inotherwords,"becomesanaliasfor"or"pointsto")theoriginalvariable. Changestothenewvariableaffecttheoriginal,andviceversa. Toassignbyreference,simplyprependanampersand(&)tothebeginningofthevariablewhichisbeing assigned(thesourcevariable).Forinstance,thefollowingcodesnippetoutputs'MynameisBob'twice: <?php $foo='Bob';//Assignthevalue'Bob'to$foo $bar=&$foo;//Reference$foovia$bar. $bar="Mynameis$bar";//Alter$bar... echo$bar; echo$foo;//$fooisalteredtoo. ?> Oneimportantthingtonoteisthatonlynamedvariablesmaybeassignedbyreference. <?php $foo=25; $bar=&$foo;//Thisisavalidassignment. $bar=&(24*7);//Invalid;referencesanunnamedexpression. functiontest() { return25; } $bar=&test();//Invalid. ?> ItisnotnecessarytoinitializevariablesinPHPhoweveritisaverygoodpractice.Uninitializedvariables haveadefaultvalueoftheirtypedependingonthecontextinwhichtheyareusedbooleansdefaultto FALSE,integersandfloatsdefaulttozero,strings(e.g.usedinecho())aresetasanemptystringandarrays becometoanemptyarray.
Example#1Defaultvaluesofuninitializedvariables <?php //UnsetANDunreferenced(nousecontext)variable;outputsNULL var_dump($unset_var); //Booleanusage;outputs'false'(Seeternaryoperatorsformoreonthis syntax) echo($unset_bool?"true\n":"false\n"); //Stringusage;outputs'string(3)"abc"' $unset_str.='abc'; var_dump($unset_str); //Integerusage;outputs'int(25)' $unset_int+=25;//0+25=>25 var_dump($unset_int); //Float/doubleusage;outputs'float(1.25)' $unset_float+=1.25; var_dump($unset_float); //Arrayusage;outputsarray(1){[3]=>string(3)"def"} $unset_arr[3]="def";//array()+array(3=>"def")=>array(3=>"def" ) var_dump($unset_arr); //Objectusage;createsnewstdClassobject(seehttp://www.php.net/manu al/en/reserved.classes.php) //Outputs:object(stdClass)#1(1){["foo"]=>string(3)"bar"} $unset_obj>foo='bar'; var_dump($unset_obj); ?> Relyingonthedefaultvalueofanuninitializedvariableisproblematicinthecaseofincludingonefileinto anotherwhichusesthesamevariablename.Itisalsoamajorsecurityriskwithregister_globalsturnedon. E_NOTICElevelerrorisissuedincaseofworkingwithuninitializedvariables,howevernotinthecaseof appendingelementstotheuninitializedarray.isset()languageconstructcanbeusedtodetectifavariable hasbeenalreadyinitialized.
PredefinedVariables
PHPprovidesalargenumberofpredefinedvariablestoanyscriptwhichitruns.Manyofthesevariables, however,cannotbefullydocumentedastheyaredependentuponwhichserverisrunning,theversionand setupoftheserver,andotherfactors.SomeofthesevariableswillnotbeavailablewhenPHPisrunonthe commandline.Foralistingofthesevariables,pleaseseethesectiononReservedPredefinedVariables. Warning InPHP4.2.0andlater,thedefaultvalueforthePHPdirectiveregister_globalsisoff.Thisisamajorchange
inPHP.Havingregister_globalsoffaffectsthesetofpredefinedvariablesavailableintheglobalscope.For example,togetDOCUMENT_ROOTyou'lluse$_SERVER['DOCUMENT_ROOT']insteadof $DOCUMENT_ROOT,or$_GET['id']fromtheURLhttp://www.example.com/test.php?id=3insteadof$id, or$_ENV['HOME']insteadof$HOME. Forrelatedinformationonthischange,readtheconfigurationentryforregister_globals,thesecuritychapter onUsingRegisterGlobals,aswellasthePHP4.1.0and4.2.0ReleaseAnnouncements. UsingtheavailablePHPReservedPredefinedVariables,likethesuperglobalarrays,ispreferred. Fromversion4.1.0onward,PHPprovidesanadditionalsetofpredefinedarrayscontainingvariablesfrom thewebserver(ifapplicable),theenvironment,anduserinput.Thesenewarraysareratherspecialinthat theyareautomaticallyglobali.e.,automaticallyavailableineveryscope.Forthisreason,theyareoften knownas"superglobals".(ThereisnomechanisminPHPforuserdefinedsuperglobals.)Thesuperglobals arelistedbelow;however,foralistingoftheircontentsandfurtherdiscussiononPHPpredefinedvariables andtheirnatures,pleaseseethesectionReservedPredefinedVariables.Also,you'llnoticehowtheolder predefinedvariables($HTTP_*_VARS)stillexist.AsofPHP5.0.0,thelongPHPpredefinedvariablearrays maybedisabledwiththeregister_long_arraysdirective. Note:Variablevariables Superglobalscannotbeusedasvariablevariablesinsidefunctionsorclassmethods. Note:EventhoughboththesuperglobalandHTTP_*_VARScanexistatthesametime;theyare notidentical,somodifyingonewillnotchangetheother. Ifcertainvariablesinvariables_orderarenotset,theirappropriatePHPpredefinedarraysarealsoleftempty.
Variablescope
Thescopeofavariableisthecontextwithinwhichitisdefined.ForthemostpartallPHPvariablesonly haveasinglescope.Thissinglescopespansincludedandrequiredfilesaswell.Forexample: <?php $a=1; include'b.inc'; ?> Herethe$avariablewillbeavailablewithintheincludedb.incscript.However,withinuserdefined functionsalocalfunctionscopeisintroduced.Anyvariableusedinsideafunctionisbydefaultlimitedtothe localfunctionscope.Forexample: <?php $a=1;/*globalscope*/ functionTest() { echo$a;/*referencetolocalscopevariable*/
Theglobalkeyword
First,anexampleuseofglobal: Example#1Usingglobal <?php $a=1; $b=2; functionSum() { global$a,$b; $b=$a+$b; } Sum(); echo$b; ?> Theabovescriptwilloutput"3".Bydeclaring$aand$bglobalwithinthefunction,allreferencestoeither variablewillrefertotheglobalversion.Thereisnolimittothenumberofglobalvariablesthatcanbe manipulatedbyafunction. AsecondwaytoaccessvariablesfromtheglobalscopeistousethespecialPHPdefined$GLOBALSarray. Thepreviousexamplecanberewrittenas: Example#2Using$GLOBALSinsteadofglobal <?php $a=1; $b=2; functionSum() { $GLOBALS['b']=$GLOBALS['a']+$GLOBALS['b']; } Sum();
echo$b; ?> The$GLOBALSarrayisanassociativearraywiththenameoftheglobalvariablebeingthekeyandthe contentsofthatvariablebeingthevalueofthearrayelement.Noticehow$GLOBALSexistsinanyscope, thisisbecause$GLOBALSisasuperglobal.Here'sanexampledemonstratingthepowerofsuperglobals: Example#3Exampledemonstratingsuperglobalsandscope <?php functiontest_global() { //Mostpredefinedvariablesaren't"super"andrequire //'global'tobeavailabletothefunctionslocalscope. global$HTTP_POST_VARS; echo$HTTP_POST_VARS['name']; //Superglobalsareavailableinanyscopeanddo //notrequire'global'.Superglobalsareavailable //asofPHP4.1.0,andHTTP_POST_VARSisnow //deemeddeprecated. echo$_POST['name']; } ?>
Usingstaticvariables
Anotherimportantfeatureofvariablescopingisthestaticvariable.Astaticvariableexistsonlyinalocal functionscope,butitdoesnotloseitsvaluewhenprogramexecutionleavesthisscope.Considerthe followingexample: Example#4Exampledemonstratingneedforstaticvariables <?php functionTest() { $a=0; echo$a; $a++; } ?> Thisfunctionisquiteuselesssinceeverytimeitiscalleditsets$ato0andprints"0".The$a++which incrementsthevariableservesnopurposesinceassoonasthefunctionexitsthe$avariabledisappears.To makeausefulcountingfunctionwhichwillnotlosetrackofthecurrentcount,the$avariableisdeclared static: Example#5Exampleuseofstaticvariables <?php functionTest()
{ static$a=0; echo$a; $a++; } ?> Now,everytimetheTest()functioniscalleditwillprintthevalueof$aandincrementit. Staticvariablesalsoprovideonewaytodealwithrecursivefunctions.Arecursivefunctionisonewhichcalls itself.Caremustbetakenwhenwritingarecursivefunctionbecauseitispossibletomakeitrecurse indefinitely.Youmustmakesureyouhaveanadequatewayofterminatingtherecursion.Thefollowing simplefunctionrecursivelycountsto10,usingthestaticvariable$counttoknowwhentostop: Example#6Staticvariableswithrecursivefunctions <?php functionTest() { static$count=0; $count++; echo$count; if($count<10){ Test(); } $count; } ?> Note:Staticvariablesmaybedeclaredasseenintheexamplesabove.Tryingtoassignvaluesto thesevariableswhicharetheresultofexpressionswillcauseaparseerror. Example#7Declaringstaticvariables <?php functionfoo(){ static$int=0;//correct static$int=1+2;//wrong(asitisanexpression) static$int=sqrt(121);//wrong(asitisanexpressiont oo) $int++; echo$int; } ?>
Referenceswithglobalandstaticvariables
TheZendEngine1,drivingPHP4,implementsthestaticandglobalmodifierforvariablesintermsof references.Forexample,atrueglobalvariableimportedinsideafunctionscopewiththeglobalstatement
actuallycreatesareferencetotheglobalvariable.Thiscanleadtounexpectedbehaviourwhichthefollowing exampleaddresses: <?php functiontest_global_ref(){ global$obj; $obj=&newstdclass; } functiontest_global_noref(){ global$obj; $obj=newstdclass; } test_global_ref(); var_dump($obj); test_global_noref(); var_dump($obj); ?> Executingthisexamplewillresultinthefollowingoutput:
NULL object(stdClass)(0){ }
Asimilarbehaviourappliestothestaticstatement.Referencesarenotstoredstatically: <?php function&get_instance_ref(){ static$obj; echo'Staticobject:'; var_dump($obj); if(!isset($obj)){ //Assignareferencetothestaticvariable $obj=&newstdclass; } $obj>property++; return$obj; } function&get_instance_noref(){ static$obj; echo'Staticobject:'; var_dump($obj); if(!isset($obj)){ //Assigntheobjecttothestaticvariable $obj=newstdclass; } $obj>property++; return$obj; }
Thisexampledemonstratesthatwhenassigningareferencetoastaticvariable,it'snotrememberedwhenyou callthe&get_instance_ref()functionasecondtime.
Variablevariables
Sometimesitisconvenienttobeabletohavevariablevariablenames.Thatis,avariablenamewhichcanbe setanduseddynamically.Anormalvariableissetwithastatementsuchas: <?php $a='hello'; ?> Avariablevariabletakesthevalueofavariableandtreatsthatasthenameofavariable.Intheabove example,hello,canbeusedasthenameofavariablebyusingtwodollarsigns.i.e. <?php $$a='world'; ?> AtthispointtwovariableshavebeendefinedandstoredinthePHPsymboltree:$awithcontents"hello" and$hellowithcontents"world".Therefore,thisstatement: <?php echo"$a${$a}"; ?> producestheexactsameoutputas: <?php echo"$a$hello";
VariablesFromExternalSources
HTMLForms(GETandPOST)
WhenaformissubmittedtoaPHPscript,theinformationfromthatformisautomaticallymadeavailableto thescript.Therearemanywaystoaccessthisinformation,forexample: Example#1AsimpleHTMLform
<formaction="foo.php"method="post"> Name:<inputtype="text"name="username"/><br/> Email:<inputtype="text"name="email"/><br/> <inputtype="submit"name="submit"value="Submitme!"/> </form>
UsingaGETformissimilarexceptyou'llusetheappropriateGETpredefinedvariableinstead.GETalso appliestotheQUERY_STRING(theinformationafterthe'?'inaURL).So,forexample, http://www.example.com/test.php?id=3containsGETdatawhichisaccessiblewith$_GET['id'].Seealso $_REQUESTandimport_request_variables(). Note:Superglobalarrays,like$_POSTand$_GET,becameavailableinPHP4.1.0 Asshown,beforePHP4.2.0thedefaultvalueforregister_globalswason.ThePHPcommunityis encouragingalltonotrelyonthisdirectiveasit'spreferredtoassumeit'soffandcodeaccordingly. Note:Themagic_quotes_gpcconfigurationdirectiveaffectsGet,PostandCookievalues.If turnedon,value(It's"PHP!")willautomagicallybecome(It\'s\"PHP!\").Escapingisneededfor DBinsertion.Seealsoaddslashes(),stripslashes()andmagic_quotes_sybase. PHPalsounderstandsarraysinthecontextofformvariables(seetherelatedfaq).Youmay,forexample, grouprelatedvariablestogether,orusethisfeaturetoretrievevaluesfromamultipleselectinput.For example,let'spostaformtoitselfanduponsubmissiondisplaythedata: Example#3Morecomplexformvariables <?php if($_POST){ echo'<pre>'; echohtmlspecialchars(print_r($_POST,true)); echo'</pre>'; } ?> <formaction=""method="post"> Name:<inputtype="text"name="personal[name]"/><br/> Email:<inputtype="text"name="personal[email]"/><br/> Beer:<br/> <selectmultiplename="beer[]"> <optionvalue="warthog">Warthog</option> <optionvalue="guinness">Guinness</option> <optionvalue="stuttgarter">StuttgarterSchwabenbru</option> </select><br/> <inputtype="submit"value="submitme!"/> </form> IMAGESUBMITvariablenames Whensubmittingaform,itispossibletouseanimageinsteadofthestandardsubmitbuttonwithataglike:
<inputtype="image"src="image.gif"name="sub"/>
Whentheuserclickssomewhereontheimage,theaccompanyingformwillbetransmittedtotheserverwith twoadditionalvariables,sub_xandsub_y.Thesecontainthecoordinatesoftheuserclickwithintheimage.
Theexperiencedmaynotethattheactualvariablenamessentbythebrowsercontainsaperiodratherthanan underscore,butPHPconvertstheperiodtoanunderscoreautomatically.
HTTPCookies
PHPtransparentlysupportsHTTPcookiesasdefinedbyNetscape'sSpec.Cookiesareamechanismfor storingdataintheremotebrowserandthustrackingoridentifyingreturnusers.Youcansetcookiesusingthe setcookie()function.CookiesarepartoftheHTTPheader,sotheSetCookiefunctionmustbecalledbefore anyoutputissenttothebrowser.Thisisthesamerestrictionasfortheheader()function.Cookiedataisthen availableintheappropriatecookiedataarrays,suchas$_COOKIE,$HTTP_COOKIE_VARSaswellasin $_REQUEST.Seethesetcookie()manualpageformoredetailsandexamples. Ifyouwishtoassignmultiplevaluestoasinglecookievariable,youmayassignitasanarray.Forexample: <?php setcookie("MyCookie[foo]",'Testing1',time()+3600); setcookie("MyCookie[bar]",'Testing2',time()+3600); ?> ThatwillcreatetwoseparatecookiesalthoughMyCookiewillnowbeasinglearrayinyourscript.Ifyou wanttosetjustonecookiewithmultiplevalues,considerusingserialize()orexplode()onthevaluefirst. Notethatacookiewillreplaceapreviouscookiebythesamenameinyourbrowserunlessthepathor domainisdifferent.So,forashoppingcartapplicationyoumaywanttokeepacounterandpassthisalong. i.e. Example#4Asetcookie()example <?php if(isset($_COOKIE['count'])){ $count=$_COOKIE['count']+1; }else{ $count=1; } setcookie('count',$count,time()+3600); setcookie("Cart[$count]",$item,time()+3600); ?>
Dotsinincomingvariablenames
Typically,PHPdoesnotalterthenamesofvariableswhentheyarepassedintoascript.However,itshould benotedthatthedot(period,fullstop)isnotavalidcharacterinaPHPvariablename.Forthereason,lookat it: <?php $varname.ext;/*invalidvariablename*/ ?> Now,whattheparserseesisavariablenamed$varname,followedbythestringconcatenationoperator, followedbythebarestring(i.e.unquotedstringwhichdoesn'tmatchanyknownkeyorreservedwords)'ext'. Obviously,thisdoesn'thavetheintendedresult. Forthisreason,itisimportanttonotethatPHPwillautomaticallyreplaceanydotsinincomingvariable
nameswithunderscores.
Determiningvariabletypes
BecausePHPdeterminesthetypesofvariablesandconvertsthem(generally)asneeded,itisnotalways obviouswhattypeagivenvariableisatanyonetime.PHPincludesseveralfunctionswhichfindoutwhat typeavariableis,suchas:gettype(),is_array(),is_float(),is_int(),is_object(),andis_string().Seealsothe chapteronTypes.
Constants
TableofContents
Magicconstants
Aconstantisanidentifier(name)forasimplevalue.Asthenamesuggests,thatvaluecannotchangeduring theexecutionofthescript(exceptformagicconstants,whicharen'tactuallyconstants).Aconstantiscase sensitivebydefault.Byconvention,constantidentifiersarealwaysuppercase. ThenameofaconstantfollowsthesamerulesasanylabelinPHP.Avalidconstantnamestartswithaletter orunderscore,followedbyanynumberofletters,numbers,orunderscores.Asaregularexpression,itwould beexpressedthusly:[azAZ_\x7f\xff][azAZ09_\x7f\xff]* Tip SeealsotheUserlandNamingGuide. Example#1Validandinvalidconstantnames <?php //Validconstantnames define("FOO","something"); define("FOO2","somethingelse"); define("FOO_BAR","somethingmore"); //Invalidconstantnames define("2FOO","something"); //Thisisvalid,butshouldbeavoided: //PHPmayonedayprovideamagicalconstant //thatwillbreakyourscript define("__FOO__","something");
Syntax
Youcandefineaconstantbyusingthedefine()function.Onceaconstantisdefined,itcanneverbechanged orundefined. Onlyscalardata(boolean,integer,floatandstring)canbecontainedinconstants.Donotdefineresource constants. Youcangetthevalueofaconstantbysimplyspecifyingitsname.Unlikewithvariables,youshouldnot prependaconstantwitha$.Youcanalsousethefunctionconstant()toreadaconstant'svalueifyouwishto obtaintheconstant'snamedynamically.Useget_defined_constants()togetalistofalldefinedconstants. Note:Constantsand(global)variablesareinadifferentnamespace.Thisimpliesthatfor exampleTRUEand$TRUEaregenerallydifferent. Ifyouuseanundefinedconstant,PHPassumesthatyoumeanthenameoftheconstantitself,justasifyou calleditasastring(CONSTANTvs"CONSTANT").AnerroroflevelE_NOTICEwillbeissuedwhenthis happens.Seealsothemanualentryonwhy$foo[bar]iswrong(unlessyoufirstdefine()barasaconstant).If yousimplywanttocheckifaconstantisset,usethedefined()function. Thesearethedifferencesbetweenconstantsandvariables:
Magicconstants
PHPprovidesalargenumberofpredefinedconstantstoanyscriptwhichitruns.Manyoftheseconstants, however,arecreatedbyvariousextensions,andwillonlybepresentwhenthoseextensionsareavailable, eitherviadynamicloadingorbecausetheyhavebeencompiledin. Therearesevenmagicalconstantsthatchangedependingonwheretheyareused.Forexample,thevalueof __LINE__dependsonthelinethatit'susedoninyourscript.Thesespecialconstantsarecaseinsensitive andareasfollows: Afew"magical"PHPconstants Name __LINE__ Thecurrentlinenumberofthefile. Thefullpathandfilenameofthefile.Ifusedinsideaninclude,thenameoftheincluded fileisreturned.SincePHP4.0.2,__FILE__alwayscontainsanabsolutepathwith symlinksresolvedwhereasinolderversionsitcontainedrelativepathundersome circumstances. Thedirectoryofthefile.Ifusedinsideaninclude,thedirectoryoftheincludedfileis returned.Thisisequivalenttodirname(__FILE__).Thisdirectorynamedoesnothavea trailingslashunlessitistherootdirectory.(AddedinPHP5.3.0.) Thefunctionname.(AddedinPHP4.3.0)AsofPHP5thisconstantreturnsthefunction nameasitwasdeclared(casesensitive).InPHP4itsvalueisalwayslowercased. Theclassname.(AddedinPHP4.3.0)AsofPHP5thisconstantreturnstheclassname asitwasdeclared(casesensitive).InPHP4itsvalueisalwayslowercased. Theclassmethodname.(AddedinPHP5.0.0)Themethodnameisreturnedasitwas declared(casesensitive). Thenameofthecurrentnamespace(casesensitive).Thisconstantisdefinedincompile time(AddedinPHP5.3.0). Description
__FILE__
__DIR__
__FUNCTION__
__CLASS__
__METHOD__
__NAMESPACE__
Seealsoget_class(),get_object_vars(),file_exists()andfunction_exists().
Expressions
ExpressionsarethemostimportantbuildingstonesofPHP.InPHP,almostanythingyouwriteisan expression.Thesimplestyetmostaccuratewaytodefineanexpressionis"anythingthathasavalue". Themostbasicformsofexpressionsareconstantsandvariables.Whenyoutype"$a=5",you'reassigning'5' into$a.'5',obviously,hasthevalue5,orinotherwords'5'isanexpressionwiththevalueof5(inthiscase, '5'isanintegerconstant). Afterthisassignment,you'dexpect$a'svaluetobe5aswell,soifyouwrote$b=$a,you'dexpectitto behavejustasifyouwrote$b=5.Inotherwords,$aisanexpressionwiththevalueof5aswell.If everythingworksright,thisisexactlywhatwillhappen. Slightlymorecomplexexamplesforexpressionsarefunctions.Forinstance,considerthefollowingfunction: <?php functionfoo() { return5; } ?> Assumingyou'refamiliarwiththeconceptoffunctions(ifyou'renot,takealookatthechapterabout functions),you'dassumethattyping$c=foo()isessentiallyjustlikewriting$c=5,andyou'reright. Functionsareexpressionswiththevalueoftheirreturnvalue.Sincefoo()returns5,thevalueofthe expression'foo()'is5.Usuallyfunctionsdon'tjustreturnastaticvaluebutcomputesomething. Ofcourse,valuesinPHPdon'thavetobeintegers,andveryoftentheyaren't.PHPsupportsfourscalarvalue types:integervalues,floatingpointvalues(float),stringvaluesandbooleanvalues(scalarvaluesarevalues thatyoucan't'break'intosmallerpieces,unlikearrays,forinstance).PHPalsosupportstwocomposite(non scalar)types:arraysandobjects.Eachofthesevaluetypescanbeassignedintovariablesorreturnedfrom functions. PHPtakesexpressionsmuchfurther,inthesamewaymanyotherlanguagesdo.PHPisanexpression orientedlanguage,inthesensethatalmosteverythingisanexpression.Considertheexamplewe'vealready dealtwith,'$a=5'.It'seasytoseethattherearetwovaluesinvolvedhere,thevalueoftheintegerconstant '5',andthevalueof$awhichisbeingupdatedto5aswell.Butthetruthisthatthere'soneadditionalvalue involvedhere,andthat'sthevalueoftheassignmentitself.Theassignmentitselfevaluatestotheassigned value,inthiscase5.Inpractice,itmeansthat'$a=5',regardlessofwhatitdoes,isanexpressionwiththe value5.Thus,writingsomethinglike'$b=($a=5)'islikewriting'$a=5;$b=5;'(asemicolonmarksthe endofastatement).Sinceassignmentsareparsedinarighttoleftorder,youcanalsowrite'$b=$a=5'. Anothergoodexampleofexpressionorientationispreandpostincrementanddecrement.UsersofPHPand manyotherlanguagesmaybefamiliarwiththenotationofvariable++andvariable.Theseareincrement anddecrementoperators.InPHP/FI2,thestatement'$a++'hasnovalue(isnotanexpression),andthusyou can'tassignitoruseitinanyway.PHPenhancestheincrement/decrementcapabilitiesbymakingthese expressionsaswell,likeinC.InPHP,likeinC,therearetwotypesofincrementpreincrementandpost increment.Bothpreincrementandpostincrementessentiallyincrementthevariable,andtheeffectonthe variableisidentical.Thedifferenceiswiththevalueoftheincrementexpression.Preincrement,whichis written'++$variable',evaluatestotheincrementedvalue(PHPincrementsthevariablebeforereadingits value,thusthename'preincrement').Postincrement,whichiswritten'$variable++'evaluatestotheoriginal
valueof$variable,beforeitwasincremented(PHPincrementsthevariableafterreadingitsvalue,thusthe name'postincrement'). Averycommontypeofexpressionsarecomparisonexpressions.Theseexpressionsevaluatetoeither FALSEorTRUE.PHPsupports>(biggerthan),>=(biggerthanorequalto),==(equal),!=(notequal),< (smallerthan)and<=(smallerthanorequalto).Thelanguagealsosupportsasetofstrictequivalence operators:===(equaltoandsametype)and!==(notequaltoornotsametype).Theseexpressionsaremost commonlyusedinsideconditionalexecution,suchasifstatements. Thelastexampleofexpressionswe'lldealwithhereiscombinedoperatorassignmentexpressions.You alreadyknowthatifyouwanttoincrement$aby1,youcansimplywrite'$a++'or'++$a'.Butwhatifyou wanttoaddmorethanonetoit,forinstance3?Youcouldwrite'$a++'multipletimes,butthisisobviously notaveryefficientorcomfortableway.Amuchmorecommonpracticeistowrite'$a=$a+3'.'$a+3' evaluatestothevalueof$aplus3,andisassignedbackinto$a,whichresultsinincrementing$aby3.In PHP,asinseveralotherlanguageslikeC,youcanwritethisinashorterway,whichwithtimewouldbecome clearerandquickertounderstandaswell.Adding3tothecurrentvalueof$acanbewritten'$a+=3'.This meansexactly"takethevalueof$a,add3toit,andassignitbackinto$a".Inadditiontobeingshorterand clearer,thisalsoresultsinfasterexecution.Thevalueof'$a+=3',likethevalueofaregularassignment,is theassignedvalue.NoticethatitisNOT3,butthecombinedvalueof$aplus3(thisisthevaluethat's assignedinto$a).Anytwoplaceoperatorcanbeusedinthisoperatorassignmentmode,forexample'$a= 5'(subtract5fromthevalueof$a),'$b*=7'(multiplythevalueof$bby7),etc. Thereisonemoreexpressionthatmayseemoddifyouhaven'tseenitinotherlanguages,theternary conditionaloperator: <?php $first?$second:$third ?> IfthevalueofthefirstsubexpressionisTRUE(nonzero),thenthesecondsubexpressionisevaluated,and thatistheresultoftheconditionalexpression.Otherwise,thethirdsubexpressionisevaluated,andthatisthe value. Thefollowingexampleshouldhelpyouunderstandpreandpostincrementandexpressionsingeneralabit better: <?php functiondouble($i) { return$i*2; } $b=$a=5;/*assignthevaluefiveintothevariable$aand$b */ $c=$a++;/*postincrement,assignoriginalvalueof$a (5)to$c*/ $e=$d=++$b;/*preincrement,assigntheincrementedvalueof $b(6)to$dand$e*/ /*atthispoint,both$dand$eareequalto6*/ $f=double($d++);/*assigntwicethevalueof$dbefore theincrement,2*6=12to$f*/
$g=double(++$e);/*assigntwicethevalueof$eafter theincrement,2*7=14to$g*/ $h=$g+=10;/*first,$gisincrementedby10andendswiththe valueof24.thevalueoftheassignment(24)is thenassignedinto$h,and$hendswiththevalue of24aswell.*/ ?> Someexpressionscanbeconsideredasstatements.Inthiscase,astatementhastheformof'expr'';'thatis,an expressionfollowedbyasemicolon.In'$b=$a=5;',$a=5isavalidexpression,butit'snotastatementby itself.'$b=$a=5;'howeverisavalidstatement. Onelastthingworthmentioningisthetruthvalueofexpressions.Inmanyevents,mainlyinconditional executionandloops,you'renotinterestedinthespecificvalueoftheexpression,butonlycareaboutwhether itmeansTRUEorFALSE.TheconstantsTRUEandFALSE(caseinsensitive)arethetwopossibleboolean values.Whennecessary,anexpressionisautomaticallyconvertedtoboolean.Seethesectionabouttype castingfordetailsabouthow. PHPprovidesafullandpowerfulimplementationofexpressions,anddocumentingitentirelygoesbeyond thescopeofthismanual.Theaboveexamplesshouldgiveyouagoodideaaboutwhatexpressionsareand howyoucanconstructusefulexpressions.Throughouttherestofthismanualwe'llwriteexprtoindicateany validPHPexpression.
Operators
TableofContents
ArithmeticOperators AssignmentOperators BitwiseOperators ComparisonOperators ErrorControlOperators ExecutionOperators Incrementing/DecrementingOperators LogicalOperators StringOperators ArrayOperators TypeOperators
OperatorPrecedence
Theprecedenceofanoperatorspecifieshow"tightly"itbindstwoexpressionstogether.Forexample,inthe expression1+5*3,theansweris16andnot18becausethemultiplication("*")operatorhasahigher precedencethantheaddition("+")operator.Parenthesesmaybeusedtoforceprecedence,ifnecessary.For instance:(1+5)*3evaluatesto18.Ifoperatorprecedenceisequal,lefttorightassociativityisused. Thefollowingtableliststheprecedenceofoperatorswiththehighestprecedenceoperatorslistedatthetop ofthetable.Operatorsonthesamelinehaveequalprecedence,inwhichcasetheirassociativitydecides whichordertoevaluatethemin. OperatorPrecedence Associativity nonassociative clonenew left [ Operators AdditionalInformation cloneandnew array() increment/decrement
nonassociative ++ nonassociative
Associativity left left left left left left right left left left left & ^ | && || ?:
Operators
AdditionalInformation bitwiseandreferences bitwise bitwise logical logical ternary assignment logical logical logical manyuses
Leftassociativitymeansthattheexpressionisevaluatedfromlefttoright,rightassociativitymeansthe opposite. Example#1Associativity <?php $a=3*3%5;//(3*3)%5=4 $a=true?0:true?1:2;//(true?0:true)?1:2=2 $a=1; $b=2; $a=$b+=3;//$a=($b+=3)>$a=5,$b=5 ?> Useparenthesestoincreasereadabilityofthecode. Note:Although=hasalowerprecedencethanmostotheroperators,PHPwillstillallow expressionssimilartothefollowing:if(!$a=foo()),inwhichcasethereturnvalueoffoo()isput into$a.
ArithmeticOperators
Rememberbasicarithmeticfromschool?Theseworkjustlikethose. ArithmeticOperators Example $a $a+$b $a$b $a*$b $a/$b $a%$b Name Negation Addition Subtraction Result Oppositeof$a. Sumof$aand$b. Differenceof$aand$b.
AssignmentOperators
Thebasicassignmentoperatoris"=".Yourfirstinclinationmightbetothinkofthisas"equalto".Don't.It reallymeansthattheleftoperandgetssettothevalueoftheexpressionontherights(thatis,"getssetto"). Thevalueofanassignmentexpressionisthevalueassigned.Thatis,thevalueof"$a=3"is3.Thisallows youtodosometrickythings: <?php $a=($b=4)+5;//$aisequalto9now,and$bhasbeensetto4. ?> Inadditiontothebasicassignmentoperator,thereare"combinedoperators"forallofthebinaryarithmetic,
arrayunionandstringoperatorsthatallowyoutouseavalueinanexpressionandthensetitsvaluetothe resultofthatexpression.Forexample: <?php $a=3; $a+=5;//sets$ato8,asifwehadsaid:$a=$a+5; $b="Hello"; $b.="There!";//sets$bto"HelloThere!",justlike$b=$b."There! "; ?> Notethattheassignmentcopiestheoriginalvariabletothenewone(assignmentbyvalue),sochangestoone willnotaffecttheother.Thismayalsohaverelevanceifyouneedtocopysomethinglikealargearrayinside atightloop.Assignmentbyreferenceisalsosupported,usingthe$var=&$othervar;syntax.'Assignmentby reference'meansthatbothvariablesenduppointingatthesamedata,andnothingiscopiedanywhere.To learnmoreaboutreferences,pleasereadReferencesexplained.AsofPHP5,objectsareassignedby referenceunlessexplicitlytoldotherwisewiththenewclonekeyword.
BitwiseOperators
Bitwiseoperatorsallowyoutoturnspecificbitswithinanintegeronoroff.Ifboththeleftandrighthand parametersarestrings,thebitwiseoperatorwilloperateonthecharacters'ASCIIvalues. <?php echo12^9;//Outputs'5' echo"12"^"9";//OutputstheBackspacecharacter(ascii8) //('1'(ascii49))^('9'(ascii57))=#8 echo"hallo"^"hello";//Outputstheasciivalues#0#4#0#0#0 //'a'^'e'=#4 echo2^"3";//Outputs1 //2^((int)"3")==1 echo"2"^3;//Outputs1 //((int)"2")^3==1 ?> BitwiseOperators Example $a&$b $a|$b Name And Or Result Bitsthataresetinboth$aand$bareset. Bitsthataresetineither$aor$bareset.
Example
Name
Result
Xor Not
Bitsthataresetin$aor$bbutnotbothareset. Bitsthataresetin$aarenotset,andviceversa.
Don'trightshiftformorethan32bitson32bitssystems.Don'tleftshiftincaseitresultstonumberlonger than32bits.
ComparisonOperators
Comparisonoperators,astheirnameimplies,allowyoutocomparetwovalues.Youmayalsobeinterested inviewingthetypecomparisontables,astheyshowexamplesofvarioustyperelatedcomparisons. ComparisonOperators Example $a==$b Equal Name TRUEif$aisequalto$b. TRUEif$aisequalto$b,andtheyareofthesametype.(introducedin PHP4) TRUEif$aisnotequalto$b. TRUEif$aisnotequalto$b. TRUEif$aisnotequalto$b,ortheyarenotofthesametype. (introducedinPHP4) TRUEif$aisstrictlylessthan$b. Result
$a===$b Identical $a!=$b $a<>$b $a!==$b $a<$b Notequal Notequal Notidentical Lessthan
Name Greaterthan
Result TRUEif$aisstrictlygreaterthan$b.
Ifyoucompareanintegerwithastring,thestringisconvertedtoanumber.Ifyoucomparetwonumerical strings,theyarecomparedasintegers.Theserulesalsoapplytotheswitchstatement. <?php var_dump(0=="a");//0==0>true var_dump("1"=="01");//1==1>true var_dump("1"=="1e0");//1==1>true switch("a"){ case0: echo"0"; break; case"a"://neverreachedbecause"a"isalreadymatchedwith0 echo"a"; break; } ?> Forvarioustypes,comparisonisdoneaccordingtothefollowingtable(inorder). ComparisonwithVariousTypes Typeof Operand1 nullorstring boolornull Typeof Operand2 string anything Result ConvertNULLto"",numericalorlexicalcomparison Converttobool,FALSE<TRUE Builtinclassescandefineitsowncomparison,differentclassesare uncomparable,sameclasscomparepropertiesthesamewayasarrays (PHP4),PHP5hasitsownexplanation
object
object
array
array
Result
Example#1Transcriptionofstandardarraycomparison <?php //Arraysarecomparedlikethiswithstandardcomparisonoperators functionstandard_array_compare($op1,$op2) { if(count($op1)<count($op2)){ return1;//$op1<$op2 }elseif(count($op1)>count($op2)){ return1;//$op1>$op2 } foreach($op1as$key=>$val){ if(!array_key_exists($key,$op2)){ returnnull;//uncomparable }elseif($val<$op2[$key]){ return1; }elseif($val>$op2[$key]){ return1; } } return0;//$op1==$op2 } ?> Seealsostrcasecmp(),strcmp(),Arrayoperators,andthemanualsectiononTypes.
TernaryOperator
Anotherconditionaloperatoristhe"?:"(orternary)operator. Example#2Assigningadefaultvalue <?php //Exampleusagefor:TernaryOperator $action=(empty($_POST['action']))?'default':$_POST['action']; //Theaboveisidenticaltothisif/elsestatement if(empty($_POST['action'])){ $action='default'; }else{ $action=$_POST['action']; }
?> Theexpression(expr1)?(expr2):(expr3)evaluatestoexpr2ifexpr1evaluatestoTRUE,andexpr3ifexpr1 evaluatestoFALSE. Note:Pleasenotethattheternaryoperatorisastatement,andthatitdoesn'tevaluatetoa variable,buttotheresultofastatement.Thisisimportanttoknowifyouwanttoreturna variablebyreference.Thestatementreturn$var==42?$a:$b;inareturnbyreference functionwillthereforenotworkandawarningisissuedinlaterPHPversions. Note:Isisrecommendedthatyouavoid"stacking"ternaryexpressions.PHP'sbehaviourwhen usingmorethanoneternaryoperatorwithinasinglestatementisnonobvious: Example#3NonobviousTernaryBehaviour <?php //onfirstglance,thefollowingappearstooutput'true' echo(true?'true':false?'t':'f'); //however,theactualoutputoftheaboveis't' //thisisbecauseternaryexpressionsareevaluatedfromleftto right //thefollowingisamoreobviousversionofthesamecodeasab ove echo((true?'true':'false')?'t':'f'); //here,youcanseethatthefirstexpressionisevaluatedto't rue',which //inturnevaluatesto(bool)true,thusreturningthetruebranc hofthe //secondternaryexpression. ?>
ErrorControlOperators
PHPsupportsoneerrorcontroloperator:theatsign(@).WhenprependedtoanexpressioninPHP,anyerror messagesthatmightbegeneratedbythatexpressionwillbeignored. Ifthetrack_errorsfeatureisenabled,anyerrormessagegeneratedbytheexpressionwillbesavedinthe variable$php_errormsg.Thisvariablewillbeoverwrittenoneacherror,socheckearlyifyouwanttouseit. <?php /*Intentionalfileerror*/ $my_file=@file('non_existent_file')or die("Failedopeningfile:errorwas'$php_errormsg'"); //thisworksforanyexpression,notjustfunctions:
$value=@$cache[$key]; //willnotissueanoticeiftheindex$keydoesn'texist. ?> Note:The@operatorworksonlyonexpressions.Asimpleruleofthumbis:ifyoucantakethe valueofsomething,youcanprependthe@operatortoit.Forinstance,youcanprependitto variables,functionandinclude()calls,constants,andsoforth.Youcannotprependittofunction orclassdefinitions,orconditionalstructuressuchasifandforeach,andsoforth. Seealsoerror_reporting()andthemanualsectionforErrorHandlingandLoggingfunctions. Warning Currentlythe"@"errorcontroloperatorprefixwillevendisableerrorreportingforcriticalerrorsthatwill terminatescriptexecution.Amongotherthings,thismeansthatifyouuse"@"tosuppresserrorsfroma certainfunctionandeitheritisn'tavailableorhasbeenmistyped,thescriptwilldierighttherewithno indicationastowhy.
ExecutionOperators
PHPsupportsoneexecutionoperator:backticks(``).Notethatthesearenotsinglequotes!PHPwillattempt toexecutethecontentsofthebackticksasashellcommand;theoutputwillbereturned(i.e.,itwon'tsimply bedumpedtooutput;itcanbeassignedtoavariable).Useofthebacktickoperatorisidenticalto shell_exec(). <?php $output=`lsal`; echo"<pre>$output</pre>"; ?> Note:Thebacktickoperatorisdisabledwhensafemodeisenabledorshell_exec()isdisabled. SeealsothemanualsectiononProgramExecutionfunctions,popen()proc_open(),andUsingPHPfromthe commandline.
Incrementing/DecrementingOperators
PHPsupportsCstylepreandpostincrementanddecrementoperators. Note:Theincrement/decrementoperatorsdonotaffectbooleanvalues.DecrementingNULL valueshasnoeffecttoo,butincrementingthemresultsin1.
Here'sasimpleexamplescript: <?php echo"<h3>Postincrement</h3>"; $a=5; echo"Shouldbe5:".$a++."<br/>\n"; echo"Shouldbe6:".$a."<br/>\n"; echo"<h3>Preincrement</h3>"; $a=5; echo"Shouldbe6:".++$a."<br/>\n"; echo"Shouldbe6:".$a."<br/>\n"; echo"<h3>Postdecrement</h3>"; $a=5; echo"Shouldbe5:".$a."<br/>\n"; echo"Shouldbe4:".$a."<br/>\n"; echo"<h3>Predecrement</h3>"; $a=5; echo"Shouldbe4:".$a."<br/>\n"; echo"Shouldbe4:".$a."<br/>\n"; ?> PHPfollowsPerl'sconventionwhendealingwitharithmeticoperationsoncharactervariablesandnotC's. Forexample,inPerl'Z'+1turnsinto'AA',whileinC'Z'+1turnsinto'['(ord('Z')==90,ord('[')==91).Note thatcharactervariablescanbeincrementedbutnotdecrementedandevensoonlyplainASCIIcharacters(a zandAZ)aresupported. Example#1ArithmeticOperationsonCharacterVariables <?php $i='W'; for($n=0;$n<6;$n++){ echo++$i."\n"; } ?> Theaboveexamplewilloutput:
X Y Z AA AB AC
Incrementingordecrementingbooleanshasnoeffect.
LogicalOperators
LogicalOperators Example Name $aand$b And $aor$b $axor$b !$a Or Xor Not Result TRUEifboth$aand$bareTRUE. TRUEifeither$aor$bisTRUE. TRUEifeither$aor$bisTRUE,butnotboth. TRUEif$aisnotTRUE. TRUEifboth$aand$bareTRUE. TRUEifeither$aor$bisTRUE.
Thereasonforthetwodifferentvariationsof"and"and"or"operatorsisthattheyoperateatdifferent precedences.(SeeOperatorPrecedence.) Example#1Logicaloperatorsillustrated <?php //foo()willnevergetcalledasthoseoperatorsareshortcircuit $a=(false&&foo()); $b=(true||foo()); $c=(falseandfoo()); $d=(trueorfoo()); //"||"hasagreaterprecedencethan"or" $e=false||true;//$ewillbeassignedto(false||true)whichistr ue $f=falseortrue;//$fwillbeassignedtofalse var_dump($e,$f);
StringOperators
Therearetwostringoperators.Thefirstistheconcatenationoperator('.'),whichreturnstheconcatenationof itsrightandleftarguments.Thesecondistheconcatenatingassignmentoperator('.='),whichappendsthe argumentontherightsidetotheargumentontheleftside.PleasereadAssignmentOperatorsformore information. <?php $a="Hello"; $b=$a."World!";//now$bcontains"HelloWorld!" $a="Hello"; $a.="World!";//now$acontains"HelloWorld!" ?> SeealsothemanualsectionsontheStringtypeandStringfunctions.
ArrayOperators
ArrayOperators Example $a+$b $a==$b Name Union Equality Unionof$aand$b. TRUEif$aand$bhavethesamekey/valuepairs. TRUEif$aand$bhavethesamekey/valuepairsinthesameorderandofthe Result
$a===$b Identity
Example
Name sametypes.
Result
Inequality Inequality
TRUEif$aisnotequalto$b. TRUEif$aisnotequalto$b.
Nonidentity TRUEif$aisnotidenticalto$b.
The+operatorappendselementsofremainingkeysfromtherighthandedarraytothelefthanded,whereas duplicatedkeysareNOToverwritten. <?php $a=array("a"=>"apple","b"=>"banana"); $b=array("a"=>"pear","b"=>"strawberry","c"=>"cherry"); $c=$a+$b;//Unionof$aand$b echo"Unionof\$aand\$b:\n"; var_dump($c); $c=$b+$a;//Unionof$band$a echo"Unionof\$band\$a:\n"; var_dump($c); ?> Whenexecuted,thisscriptwillprintthefollowing:
Unionof$aand$b: array(3){ ["a"]=> string(5)"apple" ["b"]=> string(6)"banana" ["c"]=> string(6)"cherry" } Unionof$band$a: array(3){ ["a"]=> string(4)"pear" ["b"]=> string(10)"strawberry" ["c"]=> string(6)"cherry" }
TypeOperators
instanceofisusedtodeterminewhetheraPHPvariableisaninstantiatedobjectofacertainclass: Example#1Usinginstanceofwithclasses <?php classMyClass { } classNotMyClass { } $a=newMyClass; var_dump($ainstanceofMyClass); var_dump($ainstanceofNotMyClass); ?> Theaboveexamplewilloutput:
bool(true) bool(false)
?> Theaboveexamplewilloutput:
bool(true) bool(true)
Tocheckifanobjectisnotaninstanceofaclass,thelogical not operator canbeused. Example#3Usinginstanceoftocheckifobjectisnotaninstanceofaclass <?php classMyClass { } $a=newMyClass; var_dump(!($ainstanceofstdClass)); ?> Theaboveexamplewilloutput:
bool(true)
Lastly,instanceofcanalsobeusedtodeterminewhetheravariableisaninstantiatedobjectofaclassthat implementsaninterface: Example#4Usinginstanceofforclass <?php interfaceMyInterface { } classMyClassimplementsMyInterface { } $a=newMyClass; var_dump($ainstanceofMyClass); var_dump($ainstanceofMyInterface); ?> Theaboveexamplewilloutput:
bool(true) bool(true)
<?php interfaceMyInterface { } classMyClassimplementsMyInterface { } $a=newMyClass; $b=newMyClass; $c='MyClass'; $d='NotMyClass'; var_dump($ainstanceof$b);//$bisanobjectofclassMyClass var_dump($ainstanceof$c);//$cisastring'MyClass' var_dump($ainstanceof$d);//$disastring'NotMyClass' ?> Theaboveexamplewilloutput:
bool(true) bool(true) bool(false)
ControlStructures
TableofContents
if else elseif/elseif Alternativesyntaxforcontrolstructures while dowhile for foreach break continue switch declare return require include require_once include_once
Introduction
AnyPHPscriptisbuiltoutofaseriesofstatements.Astatementcanbeanassignment,afunctioncall,a loop,aconditionalstatementorevenastatementthatdoesnothing(anemptystatement).Statementsusually endwithasemicolon.Inaddition,statementscanbegroupedintoastatementgroupbyencapsulatinga groupofstatementswithcurlybraces.Astatementgroupisastatementbyitselfaswell.Thevarious statementtypesaredescribedinthischapter.
if
Theifconstructisoneofthemostimportantfeaturesofmanylanguages,PHPincluded.Itallowsfor conditionalexecutionofcodefragments.PHPfeaturesanifstructurethatissimilartothatofC:
if(expr) statement
if($a>$b) echo"aisbiggerthanb"; ?> Oftenyou'dwanttohavemorethanonestatementtobeexecutedconditionally.Ofcourse,there'snoneedto wrapeachstatementwithanifclause.Instead,youcangroupseveralstatementsintoastatementgroup.For example,thiscodewoulddisplayaisbiggerthanbif$aisbiggerthan$b,andwouldthenassignthevalue of$ainto$b: <?php if($a>$b){ echo"aisbiggerthanb"; $b=$a; } ?> Ifstatementscanbenestedinfinitelywithinotherifstatements,whichprovidesyouwithcompleteflexibility forconditionalexecutionofthevariouspartsofyourprogram.
else
Oftenyou'dwanttoexecuteastatementifacertainconditionismet,andadifferentstatementifthe conditionisnotmet.Thisiswhatelseisfor.elseextendsanifstatementtoexecuteastatementincasethe expressionintheifstatementevaluatestoFALSE.Forexample,thefollowingcodewoulddisplayaisbigger thanbif$aisbiggerthan$b,andaisNOTbiggerthanbotherwise: <?php if($a>$b){ echo"aisbiggerthanb"; }else{ echo"aisNOTbiggerthanb"; } ?> TheelsestatementisonlyexecutediftheifexpressionevaluatedtoFALSE,andiftherewereanyelseif expressionsonlyiftheyevaluatedtoFALSEaswell(seeelseif).
elseif/elseif
elseif,asitsnamesuggests,isacombinationofifandelse.Likeelse,itextendsanifstatementtoexecutea differentstatementincasetheoriginalifexpressionevaluatestoFALSE.However,unlikeelse,itwill executethatalternativeexpressiononlyiftheelseifconditionalexpressionevaluatestoTRUE.Forexample, thefollowingcodewoulddisplayaisbiggerthanb,aequaltoboraissmallerthanb: <?php if($a>$b){ echo"aisbiggerthanb";
}elseif($a==$b){ echo"aisequaltob"; }else{ echo"aissmallerthanb"; } ?> Theremaybeseveralelseifswithinthesameifstatement.Thefirstelseifexpression(ifany)thatevaluatesto TRUEwouldbeexecuted.InPHP,youcanalsowrite'elseif'(intwowords)andthebehaviorwouldbe identicaltotheoneof'elseif'(inasingleword).Thesyntacticmeaningisslightlydifferent(ifyou'refamiliar withC,thisisthesamebehavior)butthebottomlineisthatbothwouldresultinexactlythesamebehavior. Theelseifstatementisonlyexecutediftheprecedingifexpressionandanyprecedingelseifexpressions evaluatedtoFALSE,andthecurrentelseifexpressionevaluatedtoTRUE. Note:Notethatelseifandelseifwillonlybeconsideredexactlythesamewhenusingcurly bracketsasintheaboveexample.Whenusingacolontodefineyourif/elseifconditions,you mustnotseparateelseifintotwowords,orPHPwillfailwithaparseerror. <?php /*IncorrectMethod:*/ if($a>$b): echo$a."isgreaterthan".$b; elseif($a==$b)://Willnotcompile. echo"Theabovelinecausesaparseerror."; endif; /*CorrectMethod:*/ if($a>$b): echo$a."isgreaterthan".$b; elseif($a==$b)://Notethecombinationofthewords. echo$a."equals".$b; else: echo$a."isneithergreaterthanorequalto".$b; endif; ?>
Alternativesyntaxforcontrolstructures
PHPoffersanalternativesyntaxforsomeofitscontrolstructures;namely,if,while,for,foreach,andswitch. Ineachcase,thebasicformofthealternatesyntaxistochangetheopeningbracetoacolon(:)andthe closingbracetoendif;,endwhile;,endfor;,endforeach;,orendswitch;,respectively. <?phpif($a==5):?> Aisequalto5 <?phpendif;?>
Intheaboveexample,theHTMLblock"Aisequalto5"isnestedwithinanifstatementwritteninthe alternativesyntax.TheHTMLblockwouldbedisplayedonlyif$aisequalto5. Thealternativesyntaxappliestoelseandelseifaswell.Thefollowingisanifstructurewithelseifandelsein thealternativeformat: <?php if($a==5): echo"aequals5"; echo"..."; elseif($a==6): echo"aequals6"; echo"!!!"; else: echo"aisneither5nor6"; endif; ?> Seealsowhile,for,andifforfurtherexamples.
while
whileloopsarethesimplesttypeofloopinPHP.TheybehavejustliketheirCcounterparts.Thebasicform ofawhilestatementis:
while(expr) statement
dowhile
dowhileloopsareverysimilartowhileloops,exceptthetruthexpressionischeckedattheendofeach iterationinsteadofinthebeginning.Themaindifferencefromregularwhileloopsisthatthefirstiterationof adowhileloopisguaranteedtorun(thetruthexpressionisonlycheckedattheendoftheiteration),whereas itmaynotnecessarilyrunwitharegularwhileloop(thetruthexpressionischeckedatthebeginningofeach iteration,ifitevaluatestoFALSErightfromthebeginning,theloopexecutionwouldendimmediately). Thereisjustonesyntaxfordowhileloops: <?php $i=0; do{ echo$i; }while($i>0); ?> Theaboveloopwouldrunonetimeexactly,sinceafterthefirstiteration,whentruthexpressionischecked,it evaluatestoFALSE($iisnotbiggerthan0)andtheloopexecutionends. AdvancedCusersmaybefamiliarwithadifferentusageofthedowhileloop,toallowstoppingexecutionin themiddleofcodeblocks,byencapsulatingthemwithdowhile(0),andusingthebreakstatement.The followingcodefragmentdemonstratesthis: <?php do{ if($i<5){ echo"iisnotbigenough"; break; } $i*=$factor; if($i<$minimum_limit){ break; } echo"iisok"; /*processi*/
for
forloopsarethemostcomplexloopsinPHP.TheybehaveliketheirCcounterparts.Thesyntaxofaforloop is:
for(expr1;expr2;expr3) statement
Thefirstexpression(expr1)isevaluated(executed)onceunconditionallyatthebeginningoftheloop. Inthebeginningofeachiteration,expr2isevaluated.IfitevaluatestoTRUE,theloopcontinuesandthe nestedstatement(s)areexecuted.IfitevaluatestoFALSE,theexecutionoftheloopends. Attheendofeachiteration,expr3isevaluated(executed). Eachoftheexpressionscanbeemptyorcontainmultipleexpressionsseparatedbycommas.Inexpr2,all expressionsseparatedbyacommaareevaluatedbuttheresultistakenfromthelastpart.expr2beingempty meanstheloopshouldberunindefinitely(PHPimplicitlyconsidersitasTRUE,likeC).Thismaynotbeas uselessasyoumightthink,sinceoftenyou'dwanttoendtheloopusingaconditionalbreakstatementinstead ofusingthefortruthexpression. Considerthefollowingexamples.Allofthemdisplaythenumbers1through10: <?php /*example1*/ for($i=1;$i<=10;$i++){ echo$i; } /*example2*/ for($i=1;;$i++){ if($i>10){ break; } echo$i; } /*example3*/ $i=1; for(;;){ if($i>10){
Itsacommonthingtomanyuserstoiteratethougharrayslikeintheexamplebelow. <?php /* *Thisisanarraywithsomedatawewanttomodify *whenrunningthoughtheforloop. */ $people=Array( Array('name'=>'Kalle','salt'=>856412), Array('name'=>'Pierre','salt'=>215863) ); for($i=0;$i<sizeof($people);++$i) { $people[$i]['salt']=rand(000000,999999); } ?> Theproblemliesinthesecondforexpression.Thiscodecanbeslowbecauseithastocalculatethesizeof thearrayoneachiteration.Sincethesizeneverchange,itcanbeoptimizedeasilyusinganintermediate variabletostorethesizeanduseintheloopinsteadofsizeof.Theexamplebelowillustratesthis: <?php $people=Array( Array('name'=>'Kalle','salt'=>856412), Array('name'=>'Pierre','salt'=>215863) ); for($i=0,$size=sizeof($people);$i<$size;++$i) { $people[$i]['salt']=rand(000000,999999); } ?>
foreach
PHP4introducedaforeachconstruct,muchlikePerlandsomeotherlanguages.Thissimplygivesaneasy waytoiterateoverarrays.foreachworksonlyonarrays,andwillissueanerrorwhenyoutrytouseitona variablewithadifferentdatatypeoranuninitializedvariable.Therearetwosyntaxes;thesecondisaminor butusefulextensionofthefirst:
foreach(array_expressionas$value) statement foreach(array_expressionas$key=>$value) statement
Thefirstformloopsoverthearraygivenbyarray_expression.Oneachloop,thevalueofthecurrentelement isassignedto$valueandtheinternalarraypointerisadvancedbyone(soonthenextloop,you'llbelooking atthenextelement). Thesecondformdoesthesamething,exceptthatthecurrentelement'skeywillbeassignedtothevariable $keyoneachloop. AsofPHP5,itispossibletoiterateobjectstoo. Note:Whenforeachfirststartsexecuting,theinternalarraypointerisautomaticallyresettothe firstelementofthearray.Thismeansthatyoudonotneedtocallreset()beforeaforeachloop. Note:Unlessthearrayisreferenced,foreachoperatesonacopyofthespecifiedarrayandnotthe arrayitself.foreachhassomesideeffectsonthearraypointer.Don'trelyonthearraypointer duringoraftertheforeachwithoutresettingit. AsofPHP5,youcaneasilymodifyarray'selementsbypreceding$valuewith&.Thiswillassignreference insteadofcopyingthevalue. <?php $arr=array(1,2,3,4); foreach($arras&$value){ $value=$value*2; } //$arrisnowarray(2,4,6,8) unset($value);//breakthereferencewiththelastelement ?> Thisispossibleonlyifiteratedarraycanbereferenced(i.e.isvariable). Warning Referenceofa$valueandthelastarrayelementremainevenaftertheforeachloop.Itisrecommendedto destroyitbyunset(). Note:foreachdoesnotsupporttheabilitytosuppresserrormessagesusing'@'.
Youmayhavenoticedthatthefollowingarefunctionallyidentical: <?php $arr=array("one","two","three"); reset($arr); while(list(,$value)=each($arr)){ echo"Value:$value<br/>\n"; } foreach($arras$value){ echo"Value:$value<br/>\n"; } ?> Thefollowingarealsofunctionallyidentical: <?php $arr=array("one","two","three"); reset($arr); while(list($key,$value)=each($arr)){ echo"Key:$key;Value:$value<br/>\n"; } foreach($arras$key=>$value){ echo"Key:$key;Value:$value<br/>\n"; } ?> Somemoreexamplestodemonstrateusages: <?php /*foreachexample1:valueonly*/ $a=array(1,2,3,17); foreach($aas$v){ echo"Currentvalueof\$a:$v.\n"; } /*foreachexample2:value(withitsmanualaccessnotationprintedfor illustration)*/ $a=array(1,2,3,17); $i=0;/*forillustrativepurposesonly*/ foreach($aas$v){ echo"\$a[$i]=>$v.\n"; $i++; } /*foreachexample3:keyandvalue*/ $a=array( "one"=>1, "two"=>2, "three"=>3, "seventeen"=>17 );
foreach($aas$k=>$v){ echo"\$a[$k]=>$v.\n"; } /*foreachexample4:multidimensionalarrays*/ $a=array(); $a[0][0]="a"; $a[0][1]="b"; $a[1][0]="y"; $a[1][1]="z"; foreach($aas$v1){ foreach($v1as$v2){ echo"$v2\n"; } } /*foreachexample5:dynamicarrays*/ foreach(array(1,2,3,4,5)as$v){ echo"$v\n"; } ?>
break
breakendsexecutionofthecurrentfor,foreach,while,dowhileorswitchstructure. breakacceptsanoptionalnumericargumentwhichtellsithowmanynestedenclosingstructuresaretobe brokenoutof. <?php $arr=array('one','two','three','four','stop','five'); while(list(,$val)=each($arr)){ if($val=='stop'){ break;/*Youcouldalsowrite'break1;'here.*/ } echo"$val<br/>\n"; } /*Usingtheoptionalargument.*/ $i=0; while(++$i){ switch($i){ case5: echo"At5<br/>\n"; break1;/*Exitonlytheswitch.*/ case10:
continue
continueisusedwithinloopingstructurestoskiptherestofthecurrentloopiterationandcontinueexecution attheconditionevaluationandthenthebeginningofthenextiteration. Note:NotethatinPHPtheswitchstatementisconsideredaloopingstructureforthepurposesof continue. continueacceptsanoptionalnumericargumentwhichtellsithowmanylevelsofenclosingloopsitshould skiptotheendof. <?php while(list($key,$value)=each($arr)){ if(!($key%2)){//skipoddmembers continue; } do_something_odd($value); } $i=0; while($i++<5){ echo"Outer<br/>\n"; while(1){ echo" Middle<br/>\n"; while(1){ echo" Inner<br/>\n"; continue3; } echo"Thisnevergetsoutput.<br/>\n"; } echo"Neitherdoesthis.<br/>\n"; } ?> Omittingthesemicolonaftercontinuecanleadtoconfusion.Here'sanexampleofwhatyoushouldn'tdo. <?php for($i=0;$i<5;++$i){ if($i==2) continue print"$i\n";
} ?> Onecanexpecttheresulttobe:
0 1 3 4
butthisscriptwilloutput:
2
becausethereturnvalueoftheprint()callisint(1),anditwilllookliketheoptionalnumericargument mentionedabove.
switch
TheswitchstatementissimilartoaseriesofIFstatementsonthesameexpression.Inmanyoccasions,you maywanttocomparethesamevariable(orexpression)withmanydifferentvalues,andexecuteadifferent pieceofcodedependingonwhichvalueitequalsto.Thisisexactlywhattheswitchstatementisfor. Note:Notethatunlikesomeotherlanguages,thecontinuestatementappliestoswitchandacts similartobreak.Ifyouhaveaswitchinsidealoopandwishtocontinuetothenextiterationof theouterloop,usecontinue2. Note:Notethatswitch/casedoesloosecomparision. Thefollowingtwoexamplesaretwodifferentwaystowritethesamething,oneusingaseriesofifandelseif statements,andtheotherusingtheswitchstatement: Example#1switchstructure <?php if($i==0){ echo"iequals0"; }elseif($i==1){ echo"iequals1"; }elseif($i==2){ echo"iequals2"; } switch($i){ case0: echo"iequals0"; break; case1: echo"iequals1";
break; case2: echo"iequals2"; break; } ?> Example#2switchstructureallowsusageofstrings <?php switch($i){ case"apple": echo"iisapple"; break; case"bar": echo"iisbar"; break; case"cake": echo"iiscake"; break; } ?> Itisimportanttounderstandhowtheswitchstatementisexecutedinordertoavoidmistakes.Theswitch statementexecuteslinebyline(actually,statementbystatement).Inthebeginning,nocodeisexecuted. OnlywhenacasestatementisfoundwithavaluethatmatchesthevalueoftheswitchexpressiondoesPHP begintoexecutethestatements.PHPcontinuestoexecutethestatementsuntiltheendoftheswitchblock,or thefirsttimeitseesabreakstatement.Ifyoudon'twriteabreakstatementattheendofacase'sstatement list,PHPwillgoonexecutingthestatementsofthefollowingcase.Forexample: <?php switch($i){ case0: echo"iequals0"; case1: echo"iequals1"; case2: echo"iequals2"; } ?> Here,if$iisequalto0,PHPwouldexecutealloftheechostatements!If$iisequalto1,PHPwouldexecute thelasttwoechostatements.Youwouldgettheexpectedbehavior('iequals2'wouldbedisplayed)onlyif$i isequalto2.Thus,itisimportantnottoforgetbreakstatements(eventhoughyoumaywanttoavoid supplyingthemonpurposeundercertaincircumstances). Inaswitchstatement,theconditionisevaluatedonlyonceandtheresultiscomparedtoeachcasestatement. Inanelseifstatement,theconditionisevaluatedagain.Ifyourconditionismorecomplicatedthanasimple compareand/orisinatightloop,aswitchmaybefaster. Thestatementlistforacasecanalsobeempty,whichsimplypassescontrolintothestatementlistforthe nextcase. <?php switch($i){
case0: case1: case2: echo"iislessthan3butnotnegative"; break; case3: echo"iis3"; } ?> Aspecialcaseisthedefaultcase.Thiscasematchesanythingthatwasn'tmatchedbytheothercases.For example: <?php switch($i){ case0: echo"iequals0"; break; case1: echo"iequals1"; break; case2: echo"iequals2"; break; default: echo"iisnotequalto0,1or2"; } ?> Thecaseexpressionmaybeanyexpressionthatevaluatestoasimpletype,thatis,integerorfloatingpoint numbersandstrings.Arraysorobjectscannotbeusedhereunlesstheyaredereferencedtoasimpletype. Thealternativesyntaxforcontrolstructuresissupportedwithswitches.Formoreinformation,see Alternativesyntaxforcontrolstructures. <?php switch($i): case0: echo"iequals0"; break; case1: echo"iequals1"; break; case2: echo"iequals2"; break; default: echo"iisnotequalto0,1or2"; endswitch; ?> Itspossibletouseasemicoloninsteadofacolonafteracaselike: <?php switch($beer) { case'tuborg';
declare
Thedeclareconstructisusedtosetexecutiondirectivesforablockofcode.Thesyntaxofdeclareissimilar tothesyntaxofotherflowcontrolconstructs:
declare(directive) statement
Thedirectivesectionallowsthebehaviorofthedeclareblocktobeset.Currentlyonlyonedirectiveis recognized:theticksdirective.(Seebelowformoreinformationontheticksdirective) Thestatementpartofthedeclareblockwillbeexecutedhowitisexecutedandwhatsideeffectsoccur duringexecutionmaydependonthedirectivesetinthedirectiveblock. Thedeclareconstructcanalsobeusedintheglobalscope,affectingallcodefollowingit. <?php //thesearethesame: //youcanusethis: declare(ticks=1){ //entirescripthere } //oryoucanusethis: declare(ticks=1); //entirescripthere ?>
Ticks
Caution AsofPHP5.3.0ticksaredeprecatedandwillberemovedinPHP6.0.0. AtickisaneventthatoccursforeveryNlowlevelstatementsexecutedbytheparserwithinthedeclare block.ThevalueforNisspecifiedusingticks=Nwithinthedeclareblocks'sdirectivesection.
Theevent(s)thatoccuroneachtickarespecifiedusingtheregister_tick_function().Seetheexamplebelow formoredetails.Notethatmorethanoneeventcanoccurforeachtick. Example#1ProfileasectionofPHPcode <?php //Afunctionthatrecordsthetimewhenitiscalled functionprofile($dump=FALSE) { static$profile; //Returnthetimesstoredinprofile,theneraseit if($dump){ $temp=$profile; unset($profile); return$temp; } $profile[]=microtime(); } //Setupatickhandler register_tick_function("profile"); //Initializethefunctionbeforethedeclareblock profile(); //Runablockofcode,throwatickevery2ndstatement declare(ticks=2){ for($x=1;$x<50;++$x){ echosimilar_text(md5($x),md5($x*$x)),"<br/>;"; } } //Displaythedatastoredintheprofiler print_r(profile(TRUE)); ?> TheexampleprofilesthePHPcodewithinthe'declare'block,recordingthetimeatwhicheverysecondlow levelstatementintheblockwasexecuted.Thisinformationcanthenbeusedtofindtheslowareaswithin particularsegmentsofcode.Thisprocesscanbeperformedusingothermethods:usingticksismore convenientandeasiertoimplement. Ticksarewellsuitedfordebugging,implementingsimplemultitasking,backgroundI/Oandmanyother tasks. Seealsoregister_tick_function()andunregister_tick_function().
return
Ifcalledfromwithinafunction,thereturn()statementimmediatelyendsexecutionofthecurrentfunction, andreturnsitsargumentasthevalueofthefunctioncall.return()willalsoendtheexecutionofaneval() statementorscriptfile. Ifcalledfromtheglobalscope,thenexecutionofthecurrentscriptfileisended.Ifthecurrentscriptfilewas include()edorrequire()ed,thencontrolispassedbacktothecallingfile.Furthermore,ifthecurrentscript filewasinclude()ed,thenthevaluegiventoreturn()willbereturnedasthevalueoftheinclude()call.If return()iscalledfromwithinthemainscriptfile,thenscriptexecutionends.Ifthecurrentscriptfilewas namedbytheauto_prepend_fileorauto_append_fileconfigurationoptionsinphp.ini,thenthatscriptfile's executionisended. Formoreinformation,seeReturningvalues. Note:Notethatsincereturn()isalanguageconstructandnotafunction,theparentheses surroundingitsargumentsarenotrequired.Itiscommontoleavethemout,andyouactually shoulddosoasPHPhaslessworktodointhiscase. Note:Youshouldneveruseparenthesesaroundyourreturnvariablewhenreturningbyreference, asthiswillnotwork.Youcanonlyreturnvariablesbyreference,nottheresultofastatement.If youusereturn($a);thenyou'renotreturningavariable,buttheresultoftheexpression($a) (whichis,ofcourse,thevalueof$a).
require()
Therequire()statementincludesandevaluatesthespecificfile. require()includesandevaluatesaspecificfile.Detailedinformationonhowthisinclusionworksis describedinthedocumentationforinclude(). require()andinclude()areidenticalineverywayexcepthowtheyhandlefailure.Theybothproducea Warning,butrequire()resultsinaFatalError.Inotherwords,don'thesitatetouserequire()ifyouwanta missingfiletohaltprocessingofthepage.include()doesnotbehavethisway,thescriptwillcontinue regardless.Besuretohaveanappropriateinclude_pathsettingaswell. Example#1Basicrequire()examples <?php require'prepend.php'; require$somefile; require('somefile.txt');
?> Seetheinclude()documentationformoreexamples. Note:PriortoPHP4.0.2,thefollowingapplies:require()willalwaysattempttoreadthetarget file,evenifthelineit'sonneverexecutes.Theconditionalstatementwon'taffectrequire(). However,ifthelineonwhichtherequire()occursisnotexecuted,neitherwillanyofthecodein thetargetfilebeexecuted.Similarly,loopingstructuresdonotaffectthebehaviourofrequire(). Althoughthecodecontainedinthetargetfileisstillsubjecttotheloop,therequire()itself happensonlyonce. Note:Becausethisisalanguageconstructandnotafunction,itcannotbecalledusingvariable functions Warning WindowsversionsofPHPpriortoPHP4.3.0donotsupportaccessofremotefilesviathisfunction,evenif allow_url_fopenisenabled. Seealsoinclude(),require_once(),include_once(),get_included_files(),eval(),file(),readfile(),virtual() andinclude_path.
include()
Theinclude()statementincludesandevaluatesthespecifiedfile. Thedocumentationbelowalsoappliestorequire().Thetwoconstructsareidenticalineverywayexcept howtheyhandlefailure.TheybothproduceaWarning,butrequire()resultsinaFatalError.Inotherwords, userequire()ifyouwantamissingfiletohaltprocessingofthepage.include()doesnotbehavethisway, thescriptwillcontinueregardless.Besuretohaveanappropriateinclude_pathsettingaswell.Bewarned thatparseerrorinincludedfiledoesn'tcauseprocessinghaltinginPHPversionspriortoPHP4.3.5.Since thisversion,itdoes. Filesforincludingarefirstlookedforineachinclude_pathentryrelativetothecurrentworkingdirectory, andtheninthedirectoryofcurrentscript.E.g.ifyourinclude_pathislibraries,currentworkingdirectoryis/ www/,youincludedinclude/a.phpandthereisinclude"b.php"inthatfile,b.phpisfirstlookedin /www/libraries/andthenin/www/include/.Iffilenamebeginswith./or../,itislookedonlyinthecurrent workingdirectory. Whenafileisincluded,thecodeitcontainsinheritsthevariablescopeofthelineonwhichtheinclude occurs.Anyvariablesavailableatthatlineinthecallingfilewillbeavailablewithinthecalledfile,fromthat pointforward.However,allfunctionsandclassesdefinedintheincludedfilehavetheglobalscope. Example#1Basicinclude()example
vars.php <?php $color='green'; $fruit='apple'; ?> test.php <?php echo"A$color$fruit";//A include'vars.php'; echo"A$color$fruit";//Agreenapple ?> Iftheincludeoccursinsideafunctionwithinthecallingfile,thenallofthecodecontainedinthecalledfile willbehaveasthoughithadbeendefinedinsidethatfunction.So,itwillfollowthevariablescopeofthat function.Anexceptiontothisrulearemagicconstantswhichareevaluatedbytheparserbeforetheinclude occurs. Example#2Includingwithinfunctions <?php functionfoo() { global$color; include'vars.php'; echo"A$color$fruit"; } /*vars.phpisinthescopeoffoo()so* *$fruitisNOTavailableoutsideofthis* *scope.$colorisbecausewedeclaredit* *asglobal.*/ foo();//Agreenapple echo"A$color$fruit";//Agreen ?> Whenafileisincluded,parsingdropsoutofPHPmodeandintoHTMLmodeatthebeginningofthetarget file,andresumesagainattheend.Forthisreason,anycodeinsidethetargetfilewhichshouldbeexecutedas PHPcodemustbeenclosedwithinvalidPHPstartandendtags. If"URLfopenwrappers"areenabledinPHP(whichtheyareinthedefaultconfiguration),youcanspecify thefiletobeincludedusingaURL(viaHTTPorothersupportedwrapperseeListofSupportedProtocols/ Wrappersforalistofprotocols)insteadofalocalpathname.Ifthetargetserverinterpretsthetargetfileas
PHPcode,variablesmaybepassedtotheincludedfileusingaURLrequeststringasusedwithHTTPGET. Thisisnotstrictlyspeakingthesamethingasincludingthefileandhavingitinherittheparentfile'svariable scope;thescriptisactuallybeingrunontheremoteserverandtheresultisthenbeingincludedintothelocal script. Warning WindowsversionsofPHPpriortoPHP4.3.0donotsupportaccessofremotefilesviathisfunction,evenif allow_url_fopenisenabled. Example#3include()throughHTTP <?php /*Thisexampleassumesthatwww.example.comisconfiguredtoparse.php *filesandnot.txtfiles.Also,'Works'heremeansthatthevariables *$fooand$barareavailablewithintheincludedfile.*/ //Won'twork;file.txtwasn'thandledbywww.example.comasPHP include'http://www.example.com/file.txt?foo=1&bar=2'; //Won'twork;looksforafilenamed'file.php?foo=1&bar=2'onthe //localfilesystem. include'file.php?foo=1&bar=2'; //Works. include'http://www.example.com/file.php?foo=1&bar=2'; $foo=1; $bar=2; include'file.txt';//Works. include'file.php';//Works. ?> Warning
Securitywarning
Remotefilemaybeprocessedattheremoteserver(dependingonthefileextensionandthefactiftheremote serverrunsPHPornot)butitstillhastoproduceavalidPHPscriptbecauseitwillbeprocessedatthelocal server.Ifthefilefromtheremoteservershouldbeprocessedthereandoutputtedonly,readfile()ismuch betterfunctiontouse.Otherwise,specialcareshouldbetakentosecuretheremotescripttoproduceavalid anddesiredcode. SeealsoRemotefiles,fopen()andfile()forrelatedinformation. HandlingReturns:Itispossibletoexecuteareturn()statementinsideanincludedfileinordertoterminate processinginthatfileandreturntothescriptwhichcalledit.Also,it'spossibletoreturnvaluesfrom includedfiles.Youcantakethevalueoftheincludecallasyouwouldanormalfunction.Thisisnot,
however,possiblewhenincludingremotefilesunlesstheoutputoftheremotefilehasvalidPHPstartand endtags(aswithanylocalfile).Youcandeclaretheneededvariableswithinthosetagsandtheywillbe introducedatwhicheverpointthefilewasincluded. Becauseinclude()isaspeciallanguageconstruct,parenthesesarenotneededarounditsargument.Takecare whencomparingreturnvalue. Example#4Comparingreturnvalueofinclude <?php //won'twork,evaluatedasinclude(('vars.php')=='OK'),i.e.include(' ') if(include('vars.php')=='OK'){ echo'OK'; } //works if((include'vars.php')=='OK'){ echo'OK'; } ?> Example#5include()andthereturn()statement return.php <?php $var='PHP'; return$var; ?> noreturn.php <?php $var='PHP'; ?> testreturns.php <?php $foo=include'return.php'; echo$foo;//prints'PHP' $bar=include'noreturn.php'; echo$bar;//prints1 ?> $baristhevalue1becausetheincludewassuccessful.Noticethedifferencebetweentheaboveexamples.
Thefirstusesreturn()withintheincludedfilewhiletheotherdoesnot.Ifthefilecan'tbeincluded,FALSE isreturnedandE_WARNINGisissued. Iftherearefunctionsdefinedintheincludedfile,theycanbeusedinthemainfileindependentiftheyare beforereturn()orafter.Ifthefileisincludedtwice,PHP5issuesfatalerrorbecausefunctionswerealready declared,whilePHP4doesn'tcomplainaboutfunctionsdefinedafterreturn().Itisrecommendedtouse include_once()insteadofcheckingifthefilewasalreadyincludedandconditionallyreturninsidethe includedfile. Anotherwayto"include"aPHPfileintoavariableistocapturetheoutputbyusingtheOutputControl Functionswithinclude().Forexample: Example#6UsingoutputbufferingtoincludeaPHPfileintoastring <?php $string=get_include_contents('somefile.php'); functionget_include_contents($filename){ if(is_file($filename)){ ob_start(); include$filename; $contents=ob_get_contents(); ob_end_clean(); return$contents; } returnfalse; } ?> Inordertoautomaticallyincludefileswithinscripts,seealsotheauto_prepend_fileandauto_append_file configurationoptionsinphp.ini. Note:Becausethisisalanguageconstructandnotafunction,itcannotbecalledusingvariable functions Seealsorequire(),require_once(),include_once(),get_included_files(),readfile(),virtual(),and include_path.
require_once()
Therequire_once()statementincludesandevaluatesthespecifiedfileduringtheexecutionofthescript. Thisisabehaviorsimilartotherequire()statement,withtheonlydifferencebeingthatifthecodefroma filehasalreadybeenincluded,itwillnotbeincludedagain.Seethedocumentationforrequire()formore informationonhowthisstatementworks.
require_once()shouldbeusedincaseswherethesamefilemightbeincludedandevaluatedmorethanonce duringaparticularexecutionofascript,andyouwanttobesurethatitisincludedexactlyoncetoavoid problemswithfunctionredefinitions,variablevaluereassignments,etc. Forexamplesonusingrequire_once()andinclude_once(),lookatthePEARcodeincludedinthelatest PHPsourcecodedistributions. Returnvaluesarethesameaswithinclude().Ifthefilewasalreadyincluded,thisfunctionreturnsTRUE Note:require_once()wasaddedinPHP4.0.1 Note:Beaware,thatthebehaviourofrequire_once()andinclude_once()maynotbewhatyou expectonanoncasesensitiveoperatingsystem(suchasWindows). Example#1require_once()iscaseinsensitiveonWindows <?php require_once"a.php";//thiswillincludea.php require_once"A.php";//thiswillincludea.phpagainonWindows !(PHP4only) ?> ThisbehaviourchangedinPHP5thepathisnormalizedfirstsothatC:\PROGRA~1\A.phpis realizedthesameasC:\ProgramFiles\a.phpandthefileisrequiredjustonce. Warning WindowsversionsofPHPpriortoPHP4.3.0donotsupportaccessofremotefilesviathisfunction,evenif allow_url_fopenisenabled. Seealsorequire(),include(),include_once(),get_required_files(),get_included_files(),readfile(),and virtual().
include_once()
Theinclude_once()statementincludesandevaluatesthespecifiedfileduringtheexecutionofthescript. Thisisabehaviorsimilartotheinclude()statement,withtheonlydifferencebeingthatifthecodefroma filehasalreadybeenincluded,itwillnotbeincludedagain.Asthenamesuggests,itwillbeincludedjust once. include_once()shouldbeusedincaseswherethesamefilemightbeincludedandevaluatedmorethanonce duringaparticularexecutionofascript,andyouwanttobesurethatitisincludedexactlyoncetoavoid problemswithfunctionredefinitions,variablevaluereassignments,etc. Formoreexamplesonusingrequire_once()andinclude_once(),lookatthePEARcodeincludedinthe latestPHPsourcecodedistributions.
Returnvaluesarethesameaswithinclude().Ifthefilewasalreadyincluded,thisfunctionreturnsTRUE Note:include_once()wasaddedinPHP4.0.1 Note:Beaware,thatthebehaviourofinclude_once()andrequire_once()maynotbewhatyou expectonanoncasesensitiveoperatingsystem(suchasWindows). Example#1include_once()iscaseinsensitiveonWindows <?php include_once"a.php";//thiswillincludea.php include_once"A.php";//thiswillincludea.phpagainonWindows !(PHP4only) ?> ThisbehaviourchangedinPHP5thepathisnormalizedfirstsothatC:\PROGRA~1\A.phpis realizedthesameasC:\ProgramFiles\a.phpandthefileisincludedjustonce. Warning WindowsversionsofPHPpriortoPHP4.3.0donotsupportaccessofremotefilesviathisfunction,evenif allow_url_fopenisenabled. Seealsoinclude(),require(),require_once(),get_required_files(),get_included_files(),readfile(),and virtual().
Functions
TableofContents
Userdefinedfunctions
Afunctionmaybedefinedusingsyntaxsuchasthefollowing: Example#1Pseudocodetodemonstratefunctionuses <?php
functionfoo($arg_1,$arg_2,/*...,*/$arg_n) { echo"Examplefunction.\n"; return$retval; } ?> AnyvalidPHPcodemayappearinsideafunction,evenotherfunctionsandclassdefinitions. FunctionnamesfollowthesamerulesasotherlabelsinPHP.Avalidfunctionnamestartswithaletteror underscore,followedbyanynumberofletters,numbers,orunderscores.Asaregularexpression,itwouldbe expressedthus:[azAZ_\x7f\xff][azAZ09_\x7f\xff]*. Tip SeealsotheUserlandNamingGuide. Functionsneednotbedefinedbeforetheyarereferenced,exceptwhenafunctionisconditionallydefinedas showninthetwoexamplesbelow. Whenafunctionisdefinedinaconditionalmannersuchasthetwoexamplesshown.Itsdefinitionmustbe processedpriortobeingcalled. Example#2Conditionalfunctions <?php $makefoo=true; /*Wecan'tcallfoo()fromhere sinceitdoesn'texistyet, butwecancallbar()*/ bar(); if($makefoo){ functionfoo() { echo"Idon'texistuntilprogramexecutionreachesme.\n"; } } /*Nowwecansafelycallfoo() since$makefooevaluatedtotrue*/ if($makefoo)foo(); functionbar() { echo"Iexistimmediatelyuponprogramstart.\n"; } ?>
Example#3Functionswithinfunctions <?php functionfoo() { functionbar() { echo"Idon'texistuntilfoo()iscalled.\n"; } } /*Wecan'tcallbar()yet sinceitdoesn'texist.*/ foo(); /*Nowwecancallbar(), foo()'sprocessesinghas madeitaccessible.*/ bar(); ?> AllfunctionsandclassesinPHPhavetheglobalscopetheycanbecalledoutsideafunctionevenifthey weredefinedinsideandviceversa. PHPdoesnotsupportfunctionoverloading,norisitpossibletoundefineorredefinepreviouslydeclared functions. Note:Functionnamesarecaseinsensitive,thoughitisusuallygoodformtocallfunctionsas theyappearintheirdeclaration. Bothvariablenumberofargumentsanddefaultargumentsaresupportedinfunctions.Seealsothefunction referencesforfunc_num_args(),func_get_arg(),andfunc_get_args()formoreinformation. ItispossibletocallrecursivefunctionsinPHP.Howeveravoidrecursivefunction/methodcallswithover 100200recursionlevelsasitcansmashthestackandcauseaterminationofthecurrentscript. Example#4Recursivefunctions <?php functionrecursion($a) { if($a<20){ echo"$a\n"; recursion($a+1); } } ?>
Functionarguments
Informationmaybepassedtofunctionsviatheargumentlist,whichisacommadelimitedlistofexpressions. PHPsupportspassingargumentsbyvalue(thedefault),passingbyreference,anddefaultargumentvalues. Variablelengthargumentlistsarealsosupported,seealsothefunctionreferencesforfunc_num_args(), func_get_arg(),andfunc_get_args()formoreinformation. Example#1Passingarraystofunctions <?php functiontakes_array($input) { echo"$input[0]+$input[1]=",$input[0]+$input[1]; } ?>
Makingargumentsbepassedbyreference
Bydefault,functionargumentsarepassedbyvalue(sothatifthevalueoftheargumentwithinthefunctionis changed,itdoesnotgetchangedoutsideofthefunction).Toallowafunctiontomodifyitsarguments,they mustbepassedbyreference. Tohaveanargumenttoafunctionalwayspassedbyreference,prependanampersand(&)totheargument nameinthefunctiondefinition: Example#2Passingfunctionparametersbyreference <?php functionadd_some_extra(&$string) { $string.='andsomethingextra.'; } $str='Thisisastring,'; add_some_extra($str); echo$str;//outputs'Thisisastring,andsomethingextra.' ?>
Defaultargumentvalues
AfunctionmaydefineC++styledefaultvaluesforscalarargumentsasfollows: Example#3Useofdefaultparametersinfunctions <?php functionmakecoffee($type="cappuccino") { return"Makingacupof$type.\n"; }
PHPalsoallowstheuseofarraysandthespecialtypeNULLasdefaultvalues,forexample: Example#4Usingnonscalartypesasdefaultvalues <?php functionmakecoffee($types=array("cappuccino"),$coffeeMaker=NULL) { $device=is_null($coffeeMaker)?"hands":$coffeeMaker; return"Makingacupof".join(",",$types)."with$device.\n"; } echomakecoffee(); echomakecoffee(array("cappuccino","lavazza"),"teapot"); ?> Thedefaultvaluemustbeaconstantexpression,not(forexample)avariable,aclassmemberorafunction call. Notethatwhenusingdefaultarguments,anydefaultsshouldbeontherightsideofanynondefault arguments;otherwise,thingswillnotworkasexpected.Considerthefollowingcodesnippet: Example#5Incorrectusageofdefaultfunctionarguments <?php functionmakeyogurt($type="acidophilus",$flavour) { return"Makingabowlof$type$flavour.\n"; } echomakeyogurt("raspberry");//won'tworkasexpected ?> Theoutputoftheaboveexampleis:
Warning:Missingargument2incalltomakeyogurt()in /usr/local/etc/httpd/htdocs/phptest/functest.htmlonline41 Makingabowlofraspberry.
Now,comparetheabovewiththis: Example#6Correctusageofdefaultfunctionarguments
Note:AsofPHP5,defaultvaluesmaybepassedbyreference.
Variablelengthargumentlists
PHP4andabovehassupportforvariablelengthargumentlistsinuserdefinedfunctions.Thisisreallyquite easy,usingthefunc_num_args(),func_get_arg(),andfunc_get_args()functions. Nospecialsyntaxisrequired,andargumentlistsmaystillbeexplicitlyprovidedwithfunctiondefinitions andwillbehaveasnormal.
Returningvalues
Valuesarereturnedbyusingtheoptionalreturnstatement.Anytypemaybereturned,includingarraysand objects.Thiscausesthefunctiontoenditsexecutionimmediatelyandpasscontrolbacktothelinefrom whichitwascalled.Seereturn()formoreinformation. Example#1Useofreturn() <?php functionsquare($num) { return$num*$num; } echosquare(4);//outputs'16'. ?> Afunctioncannotreturnmultiplevalues,butsimilarresultscanbeobtainedbyreturninganarray. Example#2Returninganarraytogetmultiplevalues <?php functionsmall_numbers() {
returnarray(0,1,2); } list($zero,$one,$two)=small_numbers(); ?> Toreturnareferencefromafunction,usethereferenceoperator&inboththefunctiondeclarationandwhen assigningthereturnedvaluetoavariable: Example#3Returningareferencefromafunction <?php function&returns_reference() { return$someref; } $newref=&returns_reference(); ?> Formoreinformationonreferences,pleasecheckoutReferencesExplained.
Variablefunctions
PHPsupportstheconceptofvariablefunctions.Thismeansthatifavariablenamehasparenthesesappended toit,PHPwilllookforafunctionwiththesamenameaswhateverthevariableevaluatesto,andwillattempt toexecuteit.Amongotherthings,thiscanbeusedtoimplementcallbacks,functiontables,andsoforth. Variablefunctionswon'tworkwithlanguageconstructssuchasecho(),print(),unset(),isset(),empty(), include(),require()andthelike.Utilizewrapperfunctionstomakeuseofanyoftheseconstructsasvariable functions. Example#1Variablefunctionexample <?php functionfoo(){ echo"Infoo()<br/>\n"; } functionbar($arg='') { echo"Inbar();argumentwas'$arg'.<br/>\n"; } //Thisisawrapperfunctionaroundecho functionechoit($string) { echo$string; }
$func='foo'; $func();//Thiscallsfoo() $func='bar'; $func('test');//Thiscallsbar() $func='echoit'; $func('test');//Thiscallsechoit() ?> Anobjectmethodcanalsobecalledwiththevariablefunctionssyntax. Example#2Variablemethodexample <?php classFoo { functionVariable() { $name='Bar'; $this>$name();//ThiscallstheBar()method } functionBar() { echo"ThisisBar"; } } $foo=newFoo(); $funcname="Variable"; $foo>$funcname();//Thiscalls$foo>Variable() ?> Seealsocall_user_func(),variablevariablesandfunction_exists().
Internal(builtin)functions
PHPcomesstandardwithmanyfunctionsandconstructs.TherearealsofunctionsthatrequirespecificPHP extensionscompiledin,otherwisefatal"undefinedfunction"errorswillappear.Forexample,touseimage functionssuchasimagecreatetruecolor(),PHPmustbecompiledwithGDsupport.Or,touse mysql_connect(),PHPmustbecompiledwithMySQLsupport.Therearemanycorefunctionsthatare includedineveryversionofPHP,suchasthestringandvariablefunctions.Acalltophpinfo()or get_loaded_extensions()willshowwhichextensionsareloadedintoPHP.Alsonotethatmanyextensionsare enabledbydefaultandthatthePHPmanualissplitupbyextension.Seetheconfiguration,installation,and individualextensionchapters,forinformationonhowtosetupPHP.
Readingandunderstandingafunction'sprototypeisexplainedwithinthemanualsectiontitledhowtoreada functiondefinition.It'simportanttorealizewhatafunctionreturnsorifafunctionworksdirectlyonapassed invalue.Forexample,str_replace()willreturnthemodifiedstringwhileusort()worksontheactualpassed invariableitself.Eachmanualpagealsohasspecificinformationforeachfunctionlikeinformationon functionparameters,behaviorchanges,returnvaluesforbothsuccessandfailure,andavailability information.Knowingtheseimportant(yetoftensubtle)differencesiscrucialforwritingcorrectPHPcode. Note:Iftheparametersgiventoafunctionarenotwhatitexpects,suchaspassinganarraywhere astringisexpected,thereturnvalueofthefunctionisundefined.Inthiscaseitwilllikelyreturn NULLbutthisisjustaconvention,andcannotbereliedupon. Seealsofunction_exists(),thefunctionreference,get_extension_funcs(),anddl().
ClassesandObjects(PHP4)
TableofContents
class
Aclassisacollectionofvariablesandfunctionsworkingwiththesevariables.Variablesaredefinedbyvar andfunctionsbyfunction.Aclassisdefinedusingthefollowingsyntax: <?php classCart{ var$items;//Itemsinourshoppingcart //Add$numarticlesof$artnrtothecart functionadd_item($artnr,$num){ $this>items[$artnr]+=$num; } //Take$numarticlesof$artnroutofthecart
functionremove_item($artnr,$num){ if($this>items[$artnr]>$num){ $this>items[$artnr]=$num; returntrue; }elseif($this>items[$artnr]==$num){ unset($this>items[$artnr]); returntrue; }else{ returnfalse; } } } ?> ThisdefinesaclassnamedCartthatconsistsofanassociativearrayofarticlesinthecartandtwofunctions toaddandremoveitemsfromthiscart. Warning YoucanNOTbreakupaclassdefinitionintomultiplefiles.YoualsocanNOTbreakaclassdefinitioninto multiplePHPblocks,unlessthebreakiswithinamethoddeclaration.Thefollowingwillnotwork: <?php classtest{ ?> <?php functiontest(){ print'OK'; } } ?> However,thefollowingisallowed: <?php classtest{ functiontest(){ ?> <?php print'OK'; } } ?> ThefollowingcautionarynotesarevalidforPHP4. Caution ThenamestdClassisusedinternallybyZendandisreserved.YoucannothaveaclassnamedstdClassin PHP. Caution
Thefunctionnames__sleepand__wakeuparemagicalinPHPclasses.Youcannothavefunctionswiththese namesinanyofyourclassesunlessyouwantthemagicfunctionalityassociatedwiththem.Seebelowfor moreinformation. Caution PHPreservesallfunctionnamesstartingwith__asmagical.Itisrecommendedthatyoudonotusefunction nameswith__inPHPunlessyouwantsomedocumentedmagicfunctionality. InPHP4,onlyconstantinitializersforvarvariablesareallowed.Toinitializevariableswithnonconstant values,youneedaninitializationfunctionwhichiscalledautomaticallywhenanobjectisbeingconstructed fromtheclass.Suchafunctioniscalledaconstructor(seebelow). <?php classCart{ /*NoneofthesewillworkinPHP4.*/ var$todays_date=date("Ymd"); var$name=$firstname; var$owner='Fred'.'Jones'; /*Arrayscontainingconstantvalueswill,though.*/ var$items=array("VCR","TV"); } /*Thisishowitshouldbedone.*/ classCart{ var$todays_date; var$name; var$owner; var$items=array("VCR","TV"); functionCart(){ $this>todays_date=date("Ymd"); $this>name=$GLOBALS['firstname']; /*etc...*/ } } ?> Classesaretypes,thatis,theyareblueprintsforactualvariables.Youhavetocreateavariableofthedesired typewiththenewoperator. <?php $cart=newCart; $cart>add_item("10",1); $another_cart=newCart; $another_cart>add_item("0815",3); ?> Thiscreatestheobjects$cartand$another_cart,bothoftheclassCart.Thefunctionadd_item()ofthe$cart objectisbeingcalledtoadd1itemofarticlenumber10tothe$cart.3itemsofarticlenumber0815are beingaddedto$another_cart.
Both,$cartand$another_cart,havefunctionsadd_item(),remove_item()andavariableitems.Theseare distinctfunctionsandvariables.Youcanthinkoftheobjectsassomethingsimilartodirectoriesina filesystem.InafilesystemyoucanhavetwodifferentfilesREADME.TXT,aslongastheyareindifferent directories.Justlikewithdirectorieswhereyou'llhavetotypethefullpathnameinordertoreacheachfile fromthetopleveldirectory,youhavetospecifythecompletenameofthefunctionyouwanttocall:inPHP terms,thetopleveldirectorywouldbetheglobalnamespace,andthepathnameseparatorwouldbe>.Thus, thenames$cart>itemsand$another_cart>itemsnametwodifferentvariables.Notethatthevariableis named$cart>items,not$cart>$items,thatis,avariablenameinPHPhasonlyasingledollarsign. <?php //correct,single$ $cart>items=array("10"=>1); //invalid,because$cart>$itemsbecomes$cart>"" $cart>$items=array("10"=>1); //correct,butmayormaynotbewhatwasintended: //$cart>$myvarbecomes$cart>items $myvar='items'; $cart>$myvar=array("10"=>1); ?> Withinaclassdefinition,youdonotknowunderwhichnametheobjectwillbeaccessibleinyourprogram: atthetimetheCartclasswaswritten,itwasunknownwhethertheobjectwouldbenamed$cart, $another_cart,orsomethingelselater.Thus,youcannotwrite$cart>itemswithintheCartclassitself. Instead,inordertobeabletoaccessitsownfunctionsandvariablesfromwithinaclass,onecanusethe pseudovariable$thiswhichcanbereadas'myown'or'currentobject'.Thus,'$this>items[$artnr]+=$num' canbereadas'add$numtothe$artnrcounterofmyownitemsarray'or'add$numtothe$artnrcounterof theitemsarraywithinthecurrentobject'. Note:The$thispseudovariableisnotusuallydefinedifthemethodinwhichitishostediscalled statically.Thisisnot,however,astrictrule:$thisisdefinedifamethodiscalledstaticallyfrom withinanotherobject.Inthiscase,thevalueof$thisisthatofthecallingobject.Thisis illustratedinthefollowingexample: <?php classA { functionfoo() { if(isset($this)){ echo'$thisisdefined('; echoget_class($this); echo")\n"; }else{ echo"\$thisisnotdefined.\n"; } } } classB { functionbar() {
Note:Therearesomenicefunctionstohandleclassesandobjects.Youmightwanttotakealook attheClass/ObjectFunctions.
extends
Oftenyouneedclasseswithsimilarvariablesandfunctionstoanotherexistingclass.Infact,itisgood practicetodefineagenericclasswhichcanbeusedinallyourprojectsandadaptthisclassfortheneedsof eachofyourspecificprojects.Tofacilitatethis,classescanbeextensionsofotherclasses.Theextendedor derivedclasshasallvariablesandfunctionsofthebaseclass(thisiscalled'inheritance'despitethefactthat nobodydied)andwhatyouaddintheextendeddefinition.Itisnotpossibletosubtractfromaclass,thatis, toundefineanyexistingfunctionsorvariables.Anextendedclassisalwaysdependentonasinglebaseclass, thatis,multipleinheritanceisnotsupported.Classesareextendedusingthekeyword'extends'. <?php classNamed_CartextendsCart{ var$owner; functionset_owner($name){ $this>owner=$name; } } ?> ThisdefinesaclassNamed_CartthathasallvariablesandfunctionsofCartplusanadditionalvariable $ownerandanadditionalfunctionset_owner().Youcreateanamedcarttheusualwayandcannowsetand getthecartsowner.Youcanstillusenormalcartfunctionsonnamedcarts: <?php $ncart=newNamed_Cart;//Createanamedcart $ncart>set_owner("kris");//Namethatcart
print$ncart>owner;//printthecartownersname $ncart>add_item("10",1);//(inheritedfunctionalityfromcart) ?> Thisisalsocalleda"parentchild"relationship.Youcreateaclass,parent,anduseextendstocreateanew classbasedontheparentclass:thechildclass.Youcanevenusethisnewchildclassandcreateanotherclass basedonthischildclass. Note:Classesmustbedefinedbeforetheyareused!IfyouwanttheclassNamed_Carttoextend theclassCart,youwillhavetodefinetheclassCartfirst.Ifyouwanttocreateanotherclass calledYellow_named_cartbasedontheclassNamed_CartyouhavetodefineNamed_Cartfirst. Tomakeitshort:theorderinwhichtheclassesaredefinedisimportant.
Constructors
Constructorsarefunctionsinaclassthatareautomaticallycalledwhenyoucreateanewinstanceofaclass withnew.Afunctionbecomesaconstructor,whenithasthesamenameastheclass.Ifaclasshasno constructor,theconstructorofthebaseclasswillbecalled,ifitexists. <?php classAuto_CartextendsCart{ functionAuto_Cart(){ $this>add_item("10",1); } } ?> ThisdefinesaclassAuto_CartthatisaCartplusaconstructorwhichinitializesthecartwithoneitemof articlenumber"10"eachtimeanewAuto_Cartisbeingmadewith"new".Constructorscantakearguments andtheseargumentscanbeoptional,whichmakesthemmuchmoreuseful.Tobeabletostillusetheclass withoutparameters,allparameterstoconstructorsshouldbemadeoptionalbyprovidingdefaultvalues. <?php classConstructor_CartextendsCart{ functionConstructor_Cart($item="10",$num=1){ $this>add_item($item,$num); } } //Shopthesameoldboringstuff. $default_cart=newConstructor_Cart; //Shopforreal... $different_cart=newConstructor_Cart("20",17); ?> Youalsocanusethe@operatortomuteerrorsoccurringintheconstructor,e.g.@new.
<?php classA { functionA() { echo"IamtheconstructorofA.<br/>\n"; } functionB() { echo"IamaregularfunctionnamedBinclassA.<br/>\n"; echo"IamnotaconstructorinA.<br/>\n"; } } classBextendsA { } //ThiswillcallB()asaconstructor $b=newB; ?> ThefunctionB()inclassAwillsuddenlybecomeaconstructorinclassB,althoughitwasneverintendedto be.PHP4doesnotcareifthefunctionisbeingdefinedinclassB,orifithasbeeninherited. Caution PHP4doesn'tcallconstructorsofthebaseclassautomaticallyfromaconstructorofaderivedclass.Itisyour responsibilitytopropagatethecalltoconstructorsupstreamwhereappropriate. Destructorsarefunctionsthatarecalledautomaticallywhenanobjectisdestroyed,eitherwithunset()orby simplygoingoutofscope.TherearenodestructorsinPHP.Youmayuseregister_shutdown_function() insteadtosimulatemosteffectsofdestructors.
ScopeResolutionOperator(::)
Caution ThefollowingisvalidforPHP4andlateronly. Sometimesitisusefultorefertofunctionsandvariablesinbaseclassesortorefertofunctionsinclassesthat havenotyetanyinstances.The::operatorisbeingusedforthis. <?php classA{ functionexample(){ echo"IamtheoriginalfunctionA::example().<br/>\n";
} } classBextendsA{ functionexample(){ echo"IamtheredefinedfunctionB::example().<br/>\n"; A::example(); } } //thereisnoobjectofclassA. //thiswillprint //IamtheoriginalfunctionA::example().<br/> A::example(); //createanobjectofclassB. $b=newB; //thiswillprint //IamtheredefinedfunctionB::example().<br/> //IamtheoriginalfunctionA::example().<br/> $b>example(); ?> Theaboveexamplecallsthefunctionexample()inclassA,butthereisnoobjectofclassA,sothatwe cannotwrite$a>example()orsimilar.Insteadwecallexample()asa'classfunction',thatis,asafunctionof theclassitself,notanyobjectofthatclass. Thereareclassfunctions,buttherearenoclassvariables.Infact,thereisnoobjectatallatthetimeofthe call.Thus,aclassfunctionmaynotuseanyobjectvariables(butitcanuselocalandglobalvariables),andit maynotuse$thisatall. Intheaboveexample,classBredefinesthefunctionexample().TheoriginaldefinitioninclassAis shadowedandnolongeravailable,unlessyouarereferringspecificallytotheimplementationofexample()in classAusingthe::operator.WriteA::example()todothis(infact,youshouldbewritingparent::example(), asshowninthenextsection). Inthiscontext,thereisacurrentobjectanditmayhaveobjectvariables.Thus,whenusedfromWITHINan objectfunction,youmayuse$thisandobjectvariables.
parent
Youmayfindyourselfwritingcodethatreferstovariablesandfunctionsinbaseclasses.Thisisparticularly trueifyourderivedclassisarefinementorspecialisationofcodeinyourbaseclass. Insteadofusingtheliteralnameofthebaseclassinyourcode,youshouldbeusingthespecialnameparent, whichreferstothenameofyourbaseclassasgivenintheextendsdeclarationofyourclass.Bydoingthis, youavoidusingthenameofyourbaseclassinmorethanoneplace.Shouldyourinheritancetreechange
duringimplementation,thechangeiseasilymadebysimplychangingtheextendsdeclarationofyourclass. <?php classA{ functionexample(){ echo"IamA::example()andprovidebasicfunctionality.<br/>\n" ; } } classBextendsA{ functionexample(){ echo"IamB::example()andprovideadditionalfunctionality.<br />\n"; parent::example(); } } $b=newB; //ThiswillcallB::example(),whichwillinturncallA::example(). $b>example(); ?>
Serializingobjectsobjectsinsessions
serialize()returnsastringcontainingabytestreamrepresentationofanyvaluethatcanbestoredinPHP. unserialize()canusethisstringtorecreatetheoriginalvariablevalues.Usingserializetosaveanobjectwill saveallvariablesinanobject.Thefunctionsinanobjectwillnotbesaved,onlythenameoftheclass. Inordertobeabletounserialize()anobject,theclassofthatobjectneedstobedefined.Thatis,ifyouhave anobject$aofclassAonpage1.phpandserializethis,you'llgetastringthatreferstoclassAandcontains allvaluesofvariabledcontainedin$a.Ifyouwanttobeabletounserializethisonpage2.php,recreating$a ofclassA,thedefinitionofclassAmustbepresentinpage2.php.Thiscanbedoneforexamplebystoring theclassdefinitionofclassAinanincludefileandincludingthisfileinbothpage1.phpandpage2.php. <?php //classa.inc: classA{ var$one=1; functionshow_one(){ echo$this>one; } } //page1.php: include("classa.inc");
$a=newA; $s=serialize($a); //store$ssomewherewherepage2.phpcanfindit. $fp=fopen("store","w"); fwrite($fp,$s); fclose($fp); //page2.php: //thisisneededfortheunserializetoworkproperly. include("classa.inc"); $s=implode("",@file("store")); $a=unserialize($s); //nowusethefunctionshow_one()ofthe$aobject. $a>show_one(); ?> Ifyouareusingsessionsandusesession_register()toregisterobjects,theseobjectsareserialized automaticallyattheendofeachPHPpage,andareunserializedautomaticallyoneachofthefollowing pages.Thisbasicallymeansthattheseobjectscanshowuponanyofyourpagesoncetheybecomepartof yoursession. Itisstronglyrecommendedthatyouincludetheclassdefinitionsofallsuchregisteredobjectsonallofyour pages,evenifyoudonotactuallyusetheseclassesonallofyourpages.Ifyoudon'tandanobjectisbeing unserializedwithoutitsclassdefinitionbeingpresent,itwillloseitsclassassociationandbecomeanobject ofclassstdClasswithoutanyfunctionsavailableatall,thatis,itwillbecomequiteuseless. Soifintheexampleabove$abecamepartofasessionbyrunningsession_register("a"),youshouldinclude thefileclassa.inconallofyourpages,notonlypage1.phpandpage2.php.
Themagicfunctions__sleepand__wakeup
serialize()checksifyourclasshasafunctionwiththemagicname__sleep.Ifso,thatfunctionisbeingrun priortoanyserialization.Itcancleanuptheobjectandissupposedtoreturnanarraywiththenamesofall variablesofthatobjectthatshouldbeserialized.Ifthemethoddoesn'treturnanythingthenNULLis serializedandE_NOTICEisissued. Theintendeduseof__sleepistocommitpendingdataorperformsimilarcleanuptasks.Also,thefunctionis usefulifyouhaveverylargeobjectswhichneednotbesavedcompletely. Conversely,unserialize()checksforthepresenceofafunctionwiththemagicname__wakeup.Ifpresent, thisfunctioncanreconstructanyresourcesthatobjectmayhave. Theintendeduseof__wakeupistoreestablishanydatabaseconnectionsthatmayhavebeenlostduring serializationandperformotherreinitializationtasks.
Referencesinsidetheconstructor
Creatingreferenceswithintheconstructorcanleadtoconfusingresults.Thistutoriallikesectionhelpsyou toavoidproblems. <?php classFoo{ functionFoo($name){ //createareferenceinsidetheglobalarray$globalref global$globalref; $globalref[]=&$this; //setnametopassedvalue $this>setName($name); //andputitout $this>echoName(); } functionechoName(){ echo"<br/>",$this>name; } functionsetName($name){ $this>name=$name; } } ?> Letuscheckoutifthereisadifferencebetween$bar1whichhasbeencreatedusingthecopy=operatorand $bar2whichhasbeencreatedusingthereference=&operator... <?php $bar1=newFoo('setinconstructor'); $bar1>echoName(); $globalref[0]>echoName(); /*output: setinconstructor setinconstructor setinconstructor*/ $bar2=&newFoo('setinconstructor'); $bar2>echoName(); $globalref[1]>echoName(); /*output: setinconstructor setinconstructor setinconstructor*/ ?> Apparentlythereisnodifference,butinfactthereisaverysignificantone:$bar1and$globalref[0]are
_NOT_referenced,theyareNOTthesamevariable.Thisisbecause"new"doesnotreturnareferenceby default,insteaditreturnsacopy. Note:Thereisnoperformanceloss(sincePHP4andupusereferencecounting)returningcopies insteadofreferences.Onthecontraryitismostoftenbettertosimplyworkwithcopiesinsteadof references,becausecreatingreferencestakessometimewherecreatingcopiesvirtuallytakesno time(unlessnoneofthemisalargearrayorobjectandoneofthemgetschangedandtheother(s) one(s)subsequently,thenitwouldbewisetousereferencestochangethemallconcurrently). Toprovewhatiswrittenaboveletuswatchthecodebelow. <?php //nowwewillchangethename.whatdoyouexpect? //youcouldexpectthatboth$bar1and$globalref[0]changetheirnames. .. $bar1>setName('setfromoutside'); //asmentionedbeforethisisnotthecase. $bar1>echoName(); $globalref[0]>echoName(); /*output: setfromoutside setinconstructor*/ //letusseewhatisdifferentwith$bar2and$globalref[1] $bar2>setName('setfromoutside'); //luckilytheyarenotonlyequal,theyarethesamevariable //thus$bar2>nameand$globalref[1]>namearethesametoo $bar2>echoName(); $globalref[1]>echoName(); /*output: setfromoutside setfromoutside*/ ?> Anotherfinalexample,trytounderstandit. <?php classA{ functionA($i){ $this>value=$i; //trytofigureoutwhywedonotneedareferencehere $this>b=newB($this); } functioncreateRef(){ $this>c=newB($this); } functionechoValue(){ echo"<br/>","class",get_class($this),':',$this>value; } }
classB{ functionB(&$a){ $this>a=&$a; } functionechoValue(){ echo"<br/>","class",get_class($this),':',$this>a>value; } } //trytounderstandwhyusingasimplecopyherewouldyield //inanundesiredresultinthe*markedline $a=&newA(10); $a>createRef(); $a>echoValue(); $a>b>echoValue(); $a>c>echoValue(); $a>value=11; $a>echoValue(); $a>b>echoValue();//* $a>c>echoValue(); ?> Theaboveexamplewilloutput:
classA:10 classB:10 classB:10 classA:11 classB:11 classB:11
Comparingobjects
InPHP4,objectsarecomparedinaverysimplemanner,namely:Twoobjectinstancesareequaliftheyhave thesameattributesandvalues,andareinstancesofthesameclass.Similarrulesareappliedwhencomparing twoobjectsusingtheidentityoperator(===). Ifweweretoexecutethecodeintheexamplebelow: Example#1ExampleofobjectcomparisoninPHP4 <?php functionbool2str($bool){
if($bool===false){ return'FALSE'; }else{ return'TRUE'; } } functioncompareObjects(&$o1,&$o2){ echo'o1==o2:'.bool2str($o1==$o2)."\n"; echo'o1!=o2:'.bool2str($o1!=$o2)."\n"; echo'o1===o2:'.bool2str($o1===$o2)."\n"; echo'o1!==o2:'.bool2str($o1!==$o2)."\n"; } classFlag{ var$flag; functionFlag($flag=true){ $this>flag=$flag; } } classSwitchableFlagextendsFlag{ functionturnOn(){ $this>flag=true; } functionturnOff(){ $this>flag=false; } } $o=newFlag(); $p=newFlag(false); $q=newFlag(); $r=newSwitchableFlag(); echo"Compareinstancescreatedwiththesameparameters\n"; compareObjects($o,$q); echo"\nCompareinstancescreatedwithdifferentparameters\n"; compareObjects($o,$p); echo"\nCompareaninstanceofaparentclasswithonefromasubclass\n" ; compareObjects($o,$r); ?> Theaboveexamplewilloutput:
Compareinstancescreatedwiththesameparameters o1==o2:TRUE o1!=o2:FALSE
o1===o2:TRUE o1!==o2:FALSE Compareinstancescreatedwithdifferentparameters o1==o2:FALSE o1!=o2:TRUE o1===o2:FALSE o1!==o2:TRUE Compareaninstanceofaparentclasswithonefromasubclass o1==o2:FALSE o1!=o2:TRUE o1===o2:FALSE o1!==o2:TRUE
Whichistheoutputwewillexpecttoobtaingiventhecomparisonrulesabove.Onlyinstanceswiththesame valuesfortheirattributesandfromthesameclassareconsideredequalandidentical. Eveninthecaseswherewehaveobjectcomposition,thesamecomparisonrulesapply.Intheexamplebelow wecreateacontainerclassthatstoresanassociativearrayofFlagobjects. Example#2CompoundobjectcomparisonsinPHP4 <?php classFlagSet{ var$set; functionFlagSet($flagArr=array()){ $this>set=$flagArr; } functionaddFlag($name,$flag){ $this>set[$name]=$flag; } functionremoveFlag($name){ if(array_key_exists($name,$this>set)){ unset($this>set[$name]); } } } $u=newFlagSet(); $u>addFlag('flag1',$o); $u>addFlag('flag2',$p); $v=newFlagSet(array('flag1'=>$q,'flag2'=>$p)); $w=newFlagSet(array('flag1'=>$q)); echo"\nCompositeobjectsu(o,p)andv(q,p)\n"; compareObjects($u,$v); echo"\nu(o,p)andw(q)\n"; compareObjects($u,$w); ?> Theaboveexamplewilloutput:
Compositeobjectsu(o,p)andv(q,p) o1==o2:TRUE o1!=o2:FALSE o1===o2:TRUE o1!==o2:FALSE u(o,p)andw(q) o1==o2:FALSE o1!=o2:TRUE o1===o2:FALSE o1!==o2:TRUE
ClassesandObjects(PHP5)
TableofContents
TheBasics AutoloadingObjects ConstructorsandDestructors Visibility ScopeResolutionOperator(::) StaticKeyword ClassConstants ClassAbstraction ObjectInterfaces Overloading ObjectIteration Patterns MagicMethods FinalKeyword Objectcloning Comparingobjects Reflection TypeHinting LateStaticBindings Objectsandreferences
Introduction
InPHP5thereisanewObjectModel.PHP'shandlingofobjectshasbeencompletelyrewritten,allowingfor betterperformanceandmorefeatures. Tip
SeealsotheUserlandNamingGuide.
TheBasics
class
Everyclassdefinitionbeginswiththekeywordclass,followedbyaclassname,whichcanbeanynamethat isn'tareservedwordinPHP.Followedbyapairofcurlybraces,whichcontainsthedefinitionoftheclasses membersandmethods.Apseudovariable,$thisisavailablewhenamethodiscalledfromwithinanobject context.$thisisareferencetothecallingobject(usuallytheobjecttowhichthemethodbelongs,butcanbe anotherobject,ifthemethodiscalledstaticallyfromthecontextofasecondaryobject).Thisisillustratedin thefollowingexamples: Example#1$thisvariableinobjectorientedlanguage <?php classA { functionfoo() { if(isset($this)){ echo'$thisisdefined('; echoget_class($this); echo")\n"; }else{ echo"\$thisisnotdefined.\n"; } } } classB { functionbar() { A::foo(); } } $a=newA(); $a>foo(); A::foo(); $b=newB(); $b>bar(); B::bar(); ?> Theaboveexamplewilloutput:
$thisisdefined(a) $thisisnotdefined.
$thisisdefined(b) $thisisnotdefined.
Example#2SimpleClassdefinition <?php classSimpleClass { //memberdeclaration public$var='adefaultvalue'; //methoddeclaration publicfunctiondisplayVar(){ echo$this>var; } } ?> Thedefaultvaluemustbeaconstantexpression,not(forexample)avariable,aclassmemberorafunction call. Example#3Classmembers'defaultvalue <?php classSimpleClass { //invalidmemberdeclarations: public$var1='hello'.'world'; public$var2=<<<EOD helloworld EOD; public$var3=1+2; public$var4=self::myStaticMethod(); public$var5=$myVar; //validmemberdeclarations: public$var6=myConstant; public$var7=self::classConstant; public$var8=array(true,false); } ?> Note:Therearesomenicefunctionstohandleclassesandobjects.Youmightwanttotakealook attheClass/ObjectFunctions. Unlikeheredocs,nowdocscanbeusedinanystaticdatacontext. Example#4Staticdataexample <?php classfoo{ //AsofPHP5.3.0
new
Tocreateaninstanceofaclass,anewobjectmustbecreatedandassignedtoavariable.Anobjectwill alwaysbeassignedwhencreatinganewobjectunlesstheobjecthasaconstructordefinedthatthrowsan exceptiononerror.Classesshouldbedefinedbeforeinstantiation(andinsomecasesthisisarequirement). Example#5Creatinganinstance <?php $instance=newSimpleClass(); ?> Intheclasscontext,itispossibletocreateanewobjectbynewselfandnewparent. Whenassigninganalreadycreatedinstanceofaclasstoanewvariable,thenewvariablewillaccessthe sameinstanceastheobjectthatwasassigned.Thisbehaviouristhesamewhenpassinginstancestoa function.Acopyofanalreadycreatedobjectcanbemadebycloningit. Example#6ObjectAssignment <?php $assigned=$instance; $reference=&$instance; $instance>var='$assignedwillhavethisvalue'; $instance=null;//$instanceand$referencebecomenull var_dump($instance); var_dump($reference); var_dump($assigned); ?> Theaboveexamplewilloutput:
NULL NULL object(SimpleClass)#1(1){ ["var"]=> string(30)"$assignedwillhavethisvalue" }
extends
Aclasscaninheritmethodsandmembersofanotherclassbyusingtheextendskeywordinthedeclaration.It isnotpossibletoextendmultipleclasses,aclasscanonlyinheritonebaseclass. Theinheritedmethodsandmemberscanbeoverridden,unlesstheparentclasshasdefinedamethodasfinal, byredeclaringthemwiththesamenamedefinedintheparentclass.Itispossibletoaccesstheoverridden methodsorstaticmembersbyreferencingthemwithparent:: Example#7SimpleClassInheritance <?php classExtendClassextendsSimpleClass { //Redefinetheparentmethod functiondisplayVar() { echo"Extendingclass\n"; parent::displayVar(); } } $extended=newExtendClass(); $extended>displayVar(); ?> Theaboveexamplewilloutput:
Extendingclass adefaultvalue
AutoloadingObjects
ManydeveloperswritingobjectorientedapplicationscreateonePHPsourcefileperclassdefinition.Oneof thebiggestannoyancesishavingtowritealonglistofneededincludesatthebeginningofeachscript(one foreachclass). InPHP5,thisisnolongernecessary.Youmaydefinean__autoloadfunctionwhichisautomaticallycalled incaseyouaretryingtouseaclass/interfacewhichhasn'tbeendefinedyet.Bycallingthisfunctionthe scriptingengineisgivenalastchancetoloadtheclassbeforePHPfailswithanerror. Note:Exceptionsthrownin__autoloadfunctioncannotbecaughtinthecatchblockandresults inafatalerror. Note:AutoloadingisnotavailableifusingPHPinCLIinteractivemode. Note:Iftheclassnameisusede.g.incall_user_func()thenitcancontainsomedangerous
characterssuchas../.Itisrecommendedtonotusetheuserinputinsuchfunctionsoratleast verifytheinputin__autoload(). Example#1Autoloadexample ThisexampleattemptstoloadtheclassesMyClass1andMyClass2fromthefilesMyClass1.phpand MyClass2.phprespectively. <?php function__autoload($class_name){ require_once$class_name.'.php'; } $obj=newMyClass1(); $obj2=newMyClass2(); ?> Example#2Autoloadotherexample ThisexampleattemptstoloadtheinterfaceITest. <?php function__autoload($name){ var_dump($name); } classFooimplementsITest{ } /* string(5)"ITest" Fatalerror:Interface'ITest'notfoundin... */ ?>
ConstructorsandDestructors
Constructor
void__construct([mixed$args[,$...]]) PHP5allowsdeveloperstodeclareconstructormethodsforclasses.Classeswhichhaveaconstructor methodcallthismethodoneachnewlycreatedobject,soitissuitableforanyinitializationthattheobject mayneedbeforeitisused.
Note:Parentconstructorsarenotcalledimplicitlyifthechildclassdefinesaconstructor.Inorder torunaparentconstructor,acalltoparent::__construct()withinthechildconstructoris required. Example#1usingnewunifiedconstructors <?php classBaseClass{ function__construct(){ print"InBaseClassconstructor\n"; } } classSubClassextendsBaseClass{ function__construct(){ parent::__construct(); print"InSubClassconstructor\n"; } } $obj=newBaseClass(); $obj=newSubClass(); ?> Forbackwardscompatibility,ifPHP5cannotfinda__construct()functionforagivenclass,itwillsearch fortheoldstyleconstructorfunction,bythenameoftheclass.Effectively,itmeansthattheonlycasethat wouldhavecompatibilityissuesisiftheclasshadamethodnamed__construct()whichwasusedfor differentsemantics.
Destructor
void__destruct(void) PHP5introducesadestructorconceptsimilartothatofotherobjectorientedlanguages,suchasC++.The destructormethodwillbecalledassoonasallreferencestoaparticularobjectareremovedorwhenthe objectisexplicitlydestroyedorinanyorderinshutdownsequence. Example#2DestructorExample <?php classMyDestructableClass{ function__construct(){ print"Inconstructor\n"; $this>name="MyDestructableClass"; } function__destruct(){ print"Destroying".$this>name."\n"; } } $obj=newMyDestructableClass();
Visibility
Thevisibilityofapropertyormethodcanbedefinedbyprefixingthedeclarationwiththekeywords:public, protectedorprivate.Publicdeclareditemscanbeaccessedeverywhere.Protectedlimitsaccesstoinherited andparentclasses(andtotheclassthatdefinestheitem).Privatelimitsvisibilityonlytotheclassthat definestheitem.
MembersVisibility
Classmembersmustbedefinedwithpublic,private,orprotected. Example#1Memberdeclaration <?php /** *DefineMyClass */ classMyClass { public$public='Public'; protected$protected='Protected'; private$private='Private'; functionprintHello() { echo$this>public; echo$this>protected; echo$this>private; } } $obj=newMyClass(); echo$obj>public;//Works echo$obj>protected;//FatalError echo$obj>private;//FatalError $obj>printHello();//ShowsPublic,ProtectedandPrivate
/** *DefineMyClass2 */ classMyClass2extendsMyClass { //Wecanredeclarethepublicandprotectedmethod,butnotprivate protected$protected='Protected2'; functionprintHello() { echo$this>public; echo$this>protected; echo$this>private; } } $obj2=newMyClass2(); echo$obj2>public;//Works echo$obj2>private;//Undefined echo$obj2>protected;//FatalError $obj2>printHello();//ShowsPublic,Protected2,Undefined ?> Note:ThePHP4methodofdeclaringavariablewiththevarkeywordisstillsupportedfor compatibilityreasons(asasynonymforthepublickeyword).InPHP5before5.1.3,itsusage wouldgenerateanE_STRICTwarning.
MethodVisibility
Classmethodsmustbedefinedwithpublic,private,orprotected.Methodswithoutanydeclarationare definedaspublic. Example#2MethodDeclaration <?php /** *DefineMyClass */ classMyClass { //Declareapublicconstructor publicfunction__construct(){} //Declareapublicmethod publicfunctionMyPublic(){} //Declareaprotectedmethod protectedfunctionMyProtected(){} //Declareaprivatemethod
privatefunctionMyPrivate(){} //Thisispublic functionFoo() { $this>MyPublic(); $this>MyProtected(); $this>MyPrivate(); } } $myclass=newMyClass; $myclass>MyPublic();//Works $myclass>MyProtected();//FatalError $myclass>MyPrivate();//FatalError $myclass>Foo();//Public,ProtectedandPrivatework /** *DefineMyClass2 */ classMyClass2extendsMyClass { //Thisispublic functionFoo2() { $this>MyPublic(); $this>MyProtected(); $this>MyPrivate();//FatalError } } $myclass2=newMyClass2; $myclass2>MyPublic();//Works $myclass2>Foo2();//PublicandProtectedwork,notPrivate classBar { publicfunctiontest(){ $this>testPrivate(); $this>testPublic(); } publicfunctiontestPublic(){ echo"Bar::testPublic\n"; } privatefunctiontestPrivate(){ echo"Bar::testPrivate\n"; } } classFooextendsBar { publicfunctiontestPublic(){
ScopeResolutionOperator(::)
TheScopeResolutionOperator(alsocalledPaamayimNekudotayim)orinsimplerterms,thedoublecolon, isatokenthatallowsaccesstostatic,constant,andoverriddenmembersormethodsofaclass. Whenreferencingtheseitemsfromoutsidetheclassdefinition,usethenameoftheclass. AsofPHP5.3.0,it'spossibletoreferencetheclassusingavariable.Thevariable'svaluecannotbea keyword(e.g.self,parentandstatic). PaamayimNekudotayimwould,atfirst,seemlikeastrangechoicefornamingadoublecolon.However, whilewritingtheZendEngine0.5(whichpowersPHP3),that'swhattheZendteamdecidedtocallit.It actuallydoesmeandoublecoloninHebrew! Example#1::fromoutsidetheclassdefinition <?php classMyClass{ constCONST_VALUE='Aconstantvalue'; } $classname='MyClass'; echo$classname::CONST_VALUE;//AsofPHP5.3.0 echoMyClass::CONST_VALUE; ?> Twospecialkeywordsselfandparentareusedtoaccessmembersormethodsfrominsidetheclass definition. Example#2::frominsidetheclassdefinition <?php classOtherClassextendsMyClass {
publicstatic$my_static='staticvar'; publicstaticfunctiondoubleColon(){ echoparent::CONST_VALUE."\n"; echoself::$my_static."\n"; } } $classname='OtherClass'; echo$classname::doubleColon();//AsofPHP5.3.0 OtherClass::doubleColon(); ?> Whenanextendingclassoverridestheparentsdefinitionofamethod,PHPwillnotcalltheparent'smethod. It'suptotheextendedclassonwhetherornottheparent'smethodiscalled.ThisalsoappliestoConstructors andDestructors,Overloading,andMagicmethoddefinitions. Example#3Callingaparent'smethod <?php classMyClass { protectedfunctionmyFunc(){ echo"MyClass::myFunc()\n"; } } classOtherClassextendsMyClass { //Overrideparent'sdefinition publicfunctionmyFunc() { //Butstillcalltheparentfunction parent::myFunc(); echo"OtherClass::myFunc()\n"; } } $class=newOtherClass(); $class>myFunc(); ?>
StaticKeyword
Declaringclassmembersormethodsasstaticmakesthemaccessiblewithoutneedinganinstantiationofthe class.Amemberdeclaredasstaticcannotbeaccessedwithaninstantiatedclassobject(thoughastatic methodcan). ForcompatibilitywithPHP4,ifnovisibilitydeclarationisused,thenthememberormethodwillbetreated
asifitwasdeclaredaspublic. Becausestaticmethodsarecallablewithoutaninstanceoftheobjectcreated,thepseudovariable$thisisnot availableinsidethemethoddeclaredasstatic. Staticpropertiescannotbeaccessedthroughtheobjectusingthearrowoperator>. CallingnonstaticmethodsstaticallygeneratesanE_STRICTlevelwarning. AsofPHP5.3.0,it'spossibletoreferencetheclassusingavariable.Thevariable'svaluecannotbea keyword(e.g.self,parentandstatic). Example#1Staticmemberexample <?php classFoo { publicstatic$my_static='foo'; publicfunctionstaticValue(){ returnself::$my_static; } } classBarextendsFoo { publicfunctionfooStatic(){ returnparent::$my_static; } } printFoo::$my_static."\n"; $foo=newFoo(); print$foo>staticValue()."\n"; print$foo>my_static."\n";//Undefined"Property"my_static print$foo::$my_static."\n"; $classname='Foo'; print$classname::$my_static."\n";//AsofPHP5.3.0 printBar::$my_static."\n"; $bar=newBar(); print$bar>fooStatic()."\n"; ?> Example#2Staticmethodexample <?php classFoo{ publicstaticfunctionaStaticMethod(){ //... }
ClassConstants
Itispossibletodefineconstantvaluesonaperclassbasisremainingthesameandunchangeable.Constants differfromnormalvariablesinthatyoudon'tusethe$symboltodeclareorusethem. Thevaluemustbeaconstantexpression,not(forexample)avariable,aclassmember,resultofa mathematicaloperationorafunctioncall. Itsalsopossibleforinterfacestohaveconstants.Lookattheinterfacedocumentationforexamples. AsofPHP5.3.0,it'spossibletoreferencetheclassusingavariable.Thevariable'svaluecannotbea keyword(e.g.self,parentandstatic). Example#1Definingandusingaconstant <?php classMyClass { constconstant='constantvalue'; functionshowConstant(){ echoself::constant."\n"; } } echoMyClass::constant."\n"; $classname="MyClass"; echo$classname::constant."\n";//AsofPHP5.3.0 $class=newMyClass(); $class>showConstant(); echo$class::constant."\n";//AsofPHP5.3.0 ?> Example#2Staticdataexample <?php classfoo{ //AsofPHP5.3.0 constbar=<<<'EOT' bar
ClassAbstraction
PHP5introducesabstractclassesandmethods.Itisnotallowedtocreateaninstanceofaclassthathasbeen definedasabstract.Anyclassthatcontainsatleastoneabstractmethodmustalsobeabstract.Methods definedasabstractsimplydeclarethemethod'ssignaturetheycannotdefinetheimplementation. Wheninheritingfromanabstractclass,allmethodsmarkedabstractintheparent'sclassdeclarationmustbe definedbythechild;additionally,thesemethodsmustbedefinedwiththesame(oralessrestricted) visibility.Forexample,iftheabstractmethodisdefinedasprotected,thefunctionimplementationmustbe definedaseitherprotectedorpublic,butnotprivate. Example#1Abstractclassexample <?php abstractclassAbstractClass { //ForceExtendingclasstodefinethismethod abstractprotectedfunctiongetValue(); abstractprotectedfunctionprefixValue($prefix); //Commonmethod publicfunctionprintOut(){ print$this>getValue()."\n"; } } classConcreteClass1extendsAbstractClass { protectedfunctiongetValue(){ return"ConcreteClass1"; } publicfunctionprefixValue($prefix){ return"{$prefix}ConcreteClass1"; } } classConcreteClass2extendsAbstractClass { publicfunctiongetValue(){ return"ConcreteClass2";
} publicfunctionprefixValue($prefix){ return"{$prefix}ConcreteClass2"; } } $class1=newConcreteClass1; $class1>printOut(); echo$class1>prefixValue('FOO_')."\n"; $class2=newConcreteClass2; $class2>printOut(); echo$class2>prefixValue('FOO_')."\n"; ?> Theaboveexamplewilloutput:
ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2
Oldcodethathasnouserdefinedclassesorfunctionsnamed'abstract'shouldrunwithoutmodifications.
ObjectInterfaces
Objectinterfacesallowyoutocreatecodewhichspecifieswhichmethodsaclassmustimplement,without havingtodefinehowthesemethodsarehandled. Interfacesaredefinedusingtheinterfacekeyword,inthesamewayasastandardclass,butwithoutanyof themethodshavingtheircontentsdefined. Allmethodsdeclaredinaninterfacemustbepublic,thisisthenatureofaninterface.
implements
Toimplementaninterface,theimplementsoperatorisused.Allmethodsintheinterfacemustbe implementedwithinaclass;failuretodosowillresultinafatalerror.Classesmayimplementmorethanone interfaceifdesiredbyseparatingeachinterfacewithacomma. Note:Aclasscannotimplementtwointerfacesthatsharefunctionnames,sinceitwouldcause ambiguity. Note:Interfacescanbeextendedlikeclassesusingtheextendoperator.
Constants
Itspossibleforinterfacestohaveconstants.Interfaceconstantsworksexactlylikeclassconstants.They cannotbeoverriddenbyaclass/interfacethatinheritsit.
Examples
Example#1Interfaceexample <?php //Declaretheinterface'iTemplate' interfaceiTemplate { publicfunctionsetVariable($name,$var); publicfunctiongetHtml($template); } //Implementtheinterface //Thiswillwork classTemplateimplementsiTemplate { private$vars=array(); publicfunctionsetVariable($name,$var) { $this>vars[$name]=$var; } publicfunctiongetHtml($template) { foreach($this>varsas$name=>$value){ $template=str_replace('{'.$name.'}',$value,$template) ; } return$template; } } //Thiswillnotwork //Fatalerror:ClassBadTemplatecontains1abstractmethods //andmustthereforebedeclaredabstract(iTemplate::getHtml) classBadTemplateimplementsiTemplate { private$vars=array(); publicfunctionsetVariable($name,$var) { $this>vars[$name]=$var; } } ?>
Example#2ExtendableInterfaces <?php interfacea { publicfunctionfoo(); } interfacebextendsa { publicfunctionbaz(Baz$baz); } //Thiswillwork classcimplementsb { publicfunctionfoo() { } publicfunctionbaz(Baz$baz) { } } //Thiswillnotworkandresultinafatalerror classdimplementsb { publicfunctionfoo() { } publicfunctionbaz(Foo$foo) { } } ?> Example#3Multipleinterfaceinheritance <?php interfacea { publicfunctionfoo(); } interfaceb { publicfunctionbar(); } interfacecextendsa,b { publicfunctionbaz(); }
classdimplementsc { publicfunctionfoo() { } publicfunctionbar() { } publicfunctionbaz() { } } ?> Example#4Interfaceswithconstants <?php interfacea { constb='Interfaceconstant'; } //Prints:Interfaceconstant echoa::b; //Thiswillhowevernotworkbecauseitsnotallowedto //overrideconstants.Thisisthesameconceptaswith //classconstants classbimplementsa { constb='Classconstant'; } ?> Seealsotheinstanceofoperator.
Overloading
OverloadinginPHPprovidesmeanstodynamically"create"membersandmethods.Thesedynamicentities areprocessedviamagicmethodsonecanestablishinaclassforvariousactiontypes. Theoverloadingmethodsareinvokedwheninteractingwithmembersormethodsthathavenotbeen declaredorarenotvisibleinthecurrentscope.Therestofthissectionwillusetheterms"inaccessible members"and"inaccessiblemethods"torefertothiscombinationofdeclarationandvisibility. Alloverloadingmethodsmustbedefinedaspublic. Note:Noneoftheargumentsofthesemagicmethodscanbepassedbyreference.
ChangeLog
Version 5.1.0 5.3.0 Added__isset()and__unset(). Added__callStatic().Addedwarningtoenforcepublicvisibilityandnonstatic declaration. Description
Memberoverloading
void__set(string$name,mixed$value) mixed__get(string$name) bool__isset(string$name) void__unset(string$name) __set()isrunwhenwritingdatatoinaccessiblemembers. __get()isutilizedforreadingdatafrominaccessiblemembers. __isset()istriggeredbycallingisset()orempty()oninaccessiblemembers. __unset()isinvokedwhenunset()isusedoninaccessiblemembers. The$nameargumentisthenameofthememberbeinginteractedwith.The__set()method's$value argumentspecifiesthevaluethe$name'edmembershouldbesetto. Memberoverloadingonlyworksinobjectcontext.Thesemagicmethodswillnotbetriggeredinstatic context.Thereforethesemethodscannotbedeclaredstatic. Example#1overloadingwith__get,__set,__issetand__unsetexample <?php classMemberTest{ /**Locationforoverloadeddata.*/ private$data=array(); /**Overloadingnotusedondeclaredmembers.*/ public$declared=1; /**Overloadingonlyusedonthiswhenaccessedoutsidetheclass. */ private$hidden=2; publicfunction__set($name,$value){
echo"Setting'$name'to'$value'\n"; $this>data[$name]=$value; } publicfunction__get($name){ echo"Getting'$name'\n"; if(array_key_exists($name,$this>data)){ return$this>data[$name]; } $trace=debug_backtrace(); trigger_error( 'Undefinedpropertyvia__get():'.$name. 'in'.$trace[0]['file']. 'online'.$trace[0]['line'], E_USER_NOTICE); returnnull; } /**AsofPHP5.1.0*/ publicfunction__isset($name){ echo"Is'$name'set?\n"; returnisset($this>data[$name]); } /**AsofPHP5.1.0*/ publicfunction__unset($name){ echo"Unsetting'$name'\n"; unset($this>data[$name]); } /**Notamagicmethod,justhereforexample.*/ publicfunctiongetHidden(){ return$this>hidden; } } echo"<pre>\n"; $obj=newMemberTest; $obj>a=1; echo$obj>a."\n\n"; var_dump(isset($obj>a)); unset($obj>a); var_dump(isset($obj>a)); echo"\n"; echo$obj>declared."\n\n"; echo"Let'sexperimentwiththeprivatepropertynamed'hidden':\n"; echo"Privatesarevisibleinsidetheclass,so__get()notused...\n"; echo$obj>getHidden()."\n";
Methodoverloading
mixed__call(string$name,array$arguments) mixed__callStatic(string$name,array$arguments) __call()istriggeredwheninvokinginaccessiblemethodsinanobjectcontext. __callStatic()istriggeredwheninvokinginaccessiblemethodsinastaticcontext. The$nameargumentisthenameofthemethodbeingcalled.The$argumentsargumentisanenumerated arraycontainingtheparameterspassedtothe$name'edmethod. Example#2overloadinginstantiatedmethodswith__calland___callStatic <?php classMethodTest{ publicfunction__call($name,$arguments){ //Note:valueof$nameiscasesensitive. echo"Callingobjectmethod'$name'" .implode(',',$arguments)."\n"; } /**AsofPHP5.3.0*/ publicstaticfunction__callStatic($name,$arguments){ //Note:valueof$nameiscasesensitive. echo"Callingstaticmethod'$name'" .implode(',',$arguments)."\n"; }
ObjectIteration
PHP5providesawayforobjectstobedefinedsoitispossibletoiteratethroughalistofitems,with,for exampleaforeachstatement.Bydefault,allvisiblepropertieswillbeusedfortheiteration. Example#1SimpleObjectIteration <?php classMyClass { public$var1='value1'; public$var2='value2'; public$var3='value3'; protected$protected='protectedvar'; private$private='privatevar'; functioniterateVisible(){ echo"MyClass::iterateVisible:\n"; foreach($thisas$key=>$value){ print"$key=>$value\n"; } } } $class=newMyClass(); foreach($classas$key=>$value){ print"$key=>$value\n"; } echo"\n"; $class>iterateVisible(); ?>
Theaboveexamplewilloutput:
var1=>value1 var2=>value2 var3=>value3 MyClass::iterateVisible: var1=>value1 var2=>value2 var3=>value3 protected=>protectedvar private=>privatevar
Astheoutputshows,theforeachiteratedthroughallvisiblevariablesthatcanbeaccessed.Totakeitastep furtheryoucanimplementoneofPHP5'sinternalinterfacenamedIterator.Thisallowstheobjecttodecide whatandhowtheobjectwillbeiterated. Example#2ObjectIterationimplementingIterator <?php classMyIteratorimplementsIterator { private$var=array(); publicfunction__construct($array) { if(is_array($array)){ $this>var=$array; } } publicfunctionrewind(){ echo"rewinding\n"; reset($this>var); } publicfunctioncurrent(){ $var=current($this>var); echo"current:$var\n"; return$var; } publicfunctionkey(){ $var=key($this>var); echo"key:$var\n"; return$var; } publicfunctionnext(){ $var=next($this>var); echo"next:$var\n"; return$var; } publicfunctionvalid(){ $var=$this>current()!==false;
Youcanalsodefineyourclasssothatitdoesn'thavetodefinealltheIteratorfunctionsbysimply implementingthePHP5IteratorAggregateinterface. Example#3ObjectIterationimplementingIteratorAggregate <?php classMyCollectionimplementsIteratorAggregate { private$items=array(); private$count=0; //RequireddefinitionofinterfaceIteratorAggregate publicfunctiongetIterator(){ returnnewMyIterator($this>items); } publicfunctionadd($value){ $this>items[$this>count++]=$value; } }
Note:Formoreexamplesofiterators,seetheSPLExtension.
Patterns
Patternsarewaystodescribebestpracticesandgooddesigns.Theyshowaflexiblesolutiontocommon programmingproblems.
Factory
TheFactorypatternallowsfortheinstantiationofobjectsatruntime.ItiscalledaFactoryPatternsinceitis responsiblefor"manufacturing"anobject.AParameterizedFactoryreceivesthenameoftheclassto instantiateasargument. Example#1ParameterizedFactoryMethod
<?php classExample { //Theparameterizedfactorymethod publicstaticfunctionfactory($type) { if(include_once'Drivers/'.$type.'.php'){ $classname='Driver_'.$type; returnnew$classname; }else{ thrownewException('Drivernotfound'); } } } ?> Definingthismethodinaclassallowsdriverstobeloadedonthefly.IftheExampleclasswasadatabase abstractionclass,loadingaMySQLandSQLitedrivercouldbedoneasfollows: <?php //LoadaMySQLDriver $mysql=Example::factory('MySQL'); //LoadaSQLiteDriver $sqlite=Example::factory('SQLite'); ?>
Singleton
TheSingletonpatternappliestosituationsinwhichthereneedstobeasingleinstanceofaclass.Themost commonexampleofthisisadatabaseconnection.Implementingthispatternallowsaprogrammertomake thissingleinstanceeasilyaccessiblebymanyotherobjects. Example#2SingletonFunction <?php classExample { //Holdaninstanceoftheclass privatestatic$instance; //Aprivateconstructor;preventsdirectcreationofobject privatefunction__construct() { echo'Iamconstructed'; } //Thesingletonmethod publicstaticfunctionsingleton() { if(!isset(self::$instance)){ $c=__CLASS__; self::$instance=new$c; }
returnself::$instance; } //Examplemethod publicfunctionbark() { echo'Woof!'; } //Preventuserstoclonetheinstance publicfunction__clone() { trigger_error('Cloneisnotallowed.',E_USER_ERROR); } } ?> ThisallowsasingleinstanceoftheExampleclasstoberetrieved. <?php //Thiswouldfailbecausetheconstructorisprivate $test=newExample; //Thiswillalwaysretrieveasingleinstanceoftheclass $test=Example::singleton(); $test>bark(); //ThiswillissueanE_USER_ERROR. $test_clone=clone$test; ?>
MagicMethods
Thefunctionnames__construct,__destruct(seeConstructorsandDestructors),__call,__callStatic,__get, __set,__isset,__unset(seeOverloading),__sleep,__wakeup,__toString,__set_stateand__cloneare magicalinPHPclasses.Youcannothavefunctionswiththesenamesinanyofyourclassesunlessyouwant themagicfunctionalityassociatedwiththem. Caution PHPreservesallfunctionnamesstartingwith__asmagical.Itisrecommendedthatyoudonotusefunction nameswith__inPHPunlessyouwantsomedocumentedmagicfunctionality.
__sleepand__wakeup
serialize()checksifyourclasshasafunctionwiththemagicname__sleep.Ifso,thatfunctionisexecuted priortoanyserialization.Itcancleanuptheobjectandissupposedtoreturnanarraywiththenamesofall variablesofthatobjectthatshouldbeserialized.Ifthemethoddoesn'treturnanythingthenNULLis serializedandE_NOTICEisissued. Theintendeduseof__sleepistocommitpendingdataorperformsimilarcleanuptasks.Also,thefunctionis usefulifyouhaveverylargeobjectswhichdonotneedtobesavedcompletely. Conversely,unserialize()checksforthepresenceofafunctionwiththemagicname__wakeup.Ifpresent, thisfunctioncanreconstructanyresourcesthattheobjectmayhave. Theintendeduseof__wakeupistoreestablishanydatabaseconnectionsthatmayhavebeenlostduring serializationandperformotherreinitializationtasks. Example#1Sleepandwakeup <?php classConnection{ protected$link; private$server,$username,$password,$db; publicfunction__construct($server,$username,$password,$db) { $this>server=$server; $this>username=$username; $this>password=$password; $this>db=$db; $this>connect(); } privatefunctionconnect() { $this>link=mysql_connect($this>server,$this>username,$thi s>password); mysql_select_db($this>db,$this>link); } publicfunction__sleep() { returnarray('server','username','password','db'); } publicfunction__wakeup() { $this>connect(); } } ?>
__toString
The__toStringmethodallowsaclasstodecidehowitwillreactwhenitisconvertedtoastring. Example#2Simpleexample <?php //Declareasimpleclass classTestClass { public$foo; publicfunction__construct($foo){ $this>foo=$foo; } publicfunction__toString(){ return$this>foo; } } $class=newTestClass('Hello'); echo$class; ?> Theaboveexamplewilloutput:
Hello
__set_state
Thisstaticmethodiscalledforclassesexportedbyvar_export()sincePHP5.1.0. Theonlyparameterofthismethodisanarraycontainingexportedpropertiesintheformarray('property'=> value,...). Example#3Using__set_state(sincePHP5.1.0) <?php classA { public$var1; public$var2; publicstaticfunction__set_state($an_array)//AsofPHP5.1.0 {
$obj=newA; $obj>var1=$an_array['var1']; $obj>var2=$an_array['var2']; return$obj; } } $a=newA; $a>var1=5; $a>var2='foo'; eval('$b='.var_export($a,true).';');//$b=A::__set_state(array( //'var1'=>5, //'var2'=>'foo', //)); var_dump($b); ?> Theaboveexamplewilloutput:
object(A)#2(2){ ["var1"]=> int(5) ["var2"]=> string(3)"foo" }
FinalKeyword
PHP5introducesthefinalkeyword,whichpreventschildclassesfromoverridingamethodbyprefixingthe definitionwithfinal.Iftheclassitselfisbeingdefinedfinalthenitcannotbeextended. Example#1Finalmethodsexample <?php classBaseClass{ publicfunctiontest(){ echo"BaseClass::test()called\n"; } finalpublicfunctionmoreTesting(){ echo"BaseClass::moreTesting()called\n"; } } classChildClassextendsBaseClass{ publicfunctionmoreTesting(){ echo"ChildClass::moreTesting()called\n"; }
} //ResultsinFatalerror:CannotoverridefinalmethodBaseClass::moreTe sting() ?> Example#2Finalclassexample <?php finalclassBaseClass{ publicfunctiontest(){ echo"BaseClass::test()called\n"; } //Hereitdoesn'tmatterifyouspecifythefunctionasfinalornot finalpublicfunctionmoreTesting(){ echo"BaseClass::moreTesting()called\n"; } } classChildClassextendsBaseClass{ } //ResultsinFatalerror:ClassChildClassmaynotinheritfromfinalcl ass(BaseClass) ?>
Objectcloning
Creatingacopyofanobjectwithfullyreplicatedpropertiesisnotalwaysthewantedbehavior.Agood exampleoftheneedforcopyconstructors,isifyouhaveanobjectwhichrepresentsaGTKwindowandthe objectholdstheresourceofthisGTKwindow,whenyoucreateaduplicateyoumightwanttocreateanew windowwiththesamepropertiesandhavethenewobjectholdtheresourceofthenewwindow.Another exampleisifyourobjectholdsareferencetoanotherobjectwhichitusesandwhenyoureplicatetheparent objectyouwanttocreateanewinstanceofthisotherobjectsothatthereplicahasitsownseparatecopy. Anobjectcopyiscreatedbyusingtheclonekeyword(whichcallstheobject's__clone()methodifpossible). Anobject's__clone()methodcannotbecalleddirectly.
$copy_of_object=clone$object;
public$instance; publicfunction__construct(){ $this>instance=++self::$instances; } publicfunction__clone(){ $this>instance=++self::$instances; } } classMyCloneable { public$object1; public$object2; function__clone() { //Forceacopyofthis>object,otherwise //itwillpointtosameobject. $this>object1=clone$this>object1; } } $obj=newMyCloneable(); $obj>object1=newSubObject(); $obj>object2=newSubObject(); $obj2=clone$obj; print("OriginalObject:\n"); print_r($obj); print("ClonedObject:\n"); print_r($obj2); ?> Theaboveexamplewilloutput:
OriginalObject: MyCloneableObject ( [object1]=>SubObjectObject ( [instance]=>1 ) [object2]=>SubObjectObject ( [instance]=>2 ) ) ClonedObject: MyCloneableObject
Comparingobjects
InPHP5,objectcomparisonismorecomplicatedthaninPHP4andmoreinaccordancetowhatonewill expectfromanObjectOrientedLanguage(notthatPHP5issuchalanguage). Whenusingthecomparisonoperator(==),objectvariablesarecomparedinasimplemanner,namely:Two objectinstancesareequaliftheyhavethesameattributesandvalues,andareinstancesofthesameclass. Ontheotherhand,whenusingtheidentityoperator(===),objectvariablesareidenticalifandonlyifthey refertothesameinstanceofthesameclass. Anexamplewillclarifytheserules. Example#1ExampleofobjectcomparisoninPHP5 <?php functionbool2str($bool) { if($bool===false){ return'FALSE'; }else{ return'TRUE'; } } functioncompareObjects(&$o1,&$o2) { echo'o1==o2:'.bool2str($o1==$o2)."\n"; echo'o1!=o2:'.bool2str($o1!=$o2)."\n"; echo'o1===o2:'.bool2str($o1===$o2)."\n"; echo'o1!==o2:'.bool2str($o1!==$o2)."\n"; } classFlag { public$flag; functionFlag($flag=true){
$this>flag=$flag; } } classOtherFlag { public$flag; functionOtherFlag($flag=true){ $this>flag=$flag; } } $o=newFlag(); $p=newFlag(); $q=$o; $r=newOtherFlag(); echo"Twoinstancesofthesameclass\n"; compareObjects($o,$p); echo"\nTworeferencestothesameinstance\n"; compareObjects($o,$q); echo"\nInstancesoftwodifferentclasses\n"; compareObjects($o,$r); ?> Theaboveexamplewilloutput:
Twoinstancesofthesameclass o1==o2:TRUE o1!=o2:FALSE o1===o2:FALSE o1!==o2:TRUE Tworeferencestothesameinstance o1==o2:TRUE o1!=o2:FALSE o1===o2:TRUE o1!==o2:FALSE Instancesoftwodifferentclasses o1==o2:FALSE o1!=o2:TRUE o1===o2:FALSE o1!==o2:TRUE
Note:Extensionscandefineownrulesfortheirobjectscomparison.
Reflection
TableofContents
Introduction TheReflectorinterface TheReflectionExceptionclass TheReflectionFunctionclass TheReflectionParameterclass TheReflectionClassclass TheReflectionObjectclass TheReflectionMethodclass TheReflectionPropertyclass TheReflectionExtensionclass Extendingthereflectionclasses
Introduction
PHP5comeswithacompletereflectionAPIthataddstheabilitytoreverseengineerclasses,interfaces, functionsandmethodsaswellasextensions.Additionally,thereflectionAPIalsoofferswaysofretrieving doccommentsforfunctions,classesandmethods. ThereflectionAPIisanobjectorientedextensiontotheZendEngine,consistingofthefollowingclasses: <?php classReflection{} interfaceReflector{} classReflectionExceptionextendsException{} classReflectionFunctionextendsReflectionFunctionAbstractimplementsRe flector{} classReflectionParameterimplementsReflector{} classReflectionMethodextendsReflectionFunctionAbstractimplementsRefl ector{} classReflectionClassimplementsReflector{} classReflectionObjectextendsReflectionClass{} classReflectionPropertyimplementsReflector{} classReflectionExtensionimplementsReflector{} ?> Note:Fordetailsontheseclasses,havealookatthenextchapters. Ifweweretoexecutethecodeintheexamplebelow: Example#1BasicusageofthereflectionAPI <?php Reflection::export(newReflectionClass('Exception')); ?> Theaboveexamplewilloutput:
Class[<internal>classException]{
Constants[0]{ } Staticproperties[0]{ } Staticmethods[0]{ } Properties[6]{ Property[<default>protected$message] Property[<default>private$string] Property[<default>protected$code] Property[<default>protected$file] Property[<default>protected$line] Property[<default>private$trace] } Methods[9]{ Method[<internal>finalprivatemethod__clone]{ } Method[<internal,ctor>publicmethod__construct]{ Parameters[2]{ Parameter#0[<optional>$message] Parameter#1[<optional>$code] } } Method[<internal>finalpublicmethodgetMessage]{ } Method[<internal>finalpublicmethodgetCode]{ } Method[<internal>finalpublicmethodgetFile]{ } Method[<internal>finalpublicmethodgetLine]{ } Method[<internal>finalpublicmethodgetTrace]{ } Method[<internal>finalpublicmethodgetTraceAsString]{ } Method[<internal>publicmethod__toString]{ } } }
Reflector
ReflectorisaninterfaceimplementedbyallexportableReflectionclasses. <?php interfaceReflector { publicstring__toString() publicstaticstringexport()
} ?>
ReflectionException
ReflectionExceptionextendsthestandardExceptionandisthrownbyReflectionAPI.Nospecificmethods orpropertiesareintroduced.
ReflectionFunction
TheReflectionFunctionclassletsyoureverseengineerfunctions. <?php classReflectionFunctionextendsReflectionFunctionAbstractimplementsRe flector { finalprivate__clone() publicvoid__construct(stringname) publicstring__toString() publicstaticstringexport(stringname,boolreturn) publicstringgetName() publicboolisInternal() publicboolisDisabled() publicmixedgetClosure()/*AsofPHP5.3.0*/ publicboolisUserDefined() publicstringgetFileName() publicintgetStartLine() publicintgetEndLine() publicstringgetDocComment() publicarraygetStaticVariables() publicmixedinvoke([mixedargs[,...]]) publicmixedinvokeArgs(arrayargs) publicboolreturnsReference() publicReflectionParameter[]getParameters() publicintgetNumberOfParameters() publicintgetNumberOfRequiredParameters() } ?> ParentclassReflectionFunctionAbstracthasthesamemethodsexceptinvoke(),invokeArgs(),export() andisDisabled(). Note:getNumberOfParameters()andgetNumberOfRequiredParameters()wereaddedin PHP5.0.3,whileinvokeArgs()wasaddedinPHP5.1.0. Tointrospectafunction,youwillfirsthavetocreateaninstanceoftheReflectionFunctionclass.Youcan thencallanyoftheabovemethodsonthisinstance. Example#2UsingtheReflectionFunctionclass <?php
/** *Asimplecounter * *@returnint */ functioncounter() { static$c=0; return$c++; } //CreateaninstanceoftheReflectionFunctionclass $func=newReflectionFunction('counter'); //Printoutbasicinformation printf( "===>The%sfunction'%s'\n". "declaredin%s\n". "lines%dto%d\n", $func>isInternal()?'internal':'userdefined', $func>getName(), $func>getFileName(), $func>getStartLine(), $func>getEndline() ); //Printdocumentationcomment printf(">Documentation:\n%s\n",var_export($func>getDocComment(), 1)); //Printstaticvariablesifexistant if($statics=$func>getStaticVariables()) { printf(">Staticvariables:%s\n",var_export($statics,1)); } //Invokethefunction printf(">Invokationresultsin:"); var_dump($func>invoke()); //youmayprefertousetheexport()method echo"\nReflectionFunction::export()results:\n"; echoReflectionFunction::export('counter'); ?> Note:Themethodinvoke()acceptsavariablenumberofargumentswhicharepassedtothe functionjustasincall_user_func().
ReflectionParameter
TheReflectionParameterclassretrievesinformationaboutafunction'sormethod'sparameters.
<?php classReflectionParameterimplementsReflector { finalprivate__clone() publicvoid__construct(stringfunction,stringparameter) publicstring__toString() publicstaticstringexport(mixedfunction,mixedparameter,boolret urn) publicstringgetName() publicboolisPassedByReference() publicReflectionClassgetDeclaringClass() publicReflectionClassgetClass() publicboolisArray() publicboolallowsNull() publicboolisPassedByReference() publicboolisOptional() publicboolisDefaultValueAvailable() publicmixedgetDefaultValue() publicintgetPosition() } ?> Note:getDefaultValue(),isDefaultValueAvailable()andisOptional()wereaddedinPHP 5.0.3,whileisArray()wasaddedinPHP5.1.0.getDeclaringFunction()andgetPosition()were addedinPHP5.2.3. Tointrospectfunctionparameters,youwillfirsthavetocreateaninstanceoftheReflectionFunctionor ReflectionMethodclassesandthenusetheirgetParameters()methodtoretrieveanarrayofparameters. Example#3UsingtheReflectionParameterclass <?php functionfoo($a,$b,$c){} functionbar(Exception$a,&$b,$c){} functionbaz(ReflectionFunction$a,$b=1,$c=null){} functionabc(){} //CreateaninstanceofReflectionFunctionwiththe //parametergivenfromthecommandline. $reflect=newReflectionFunction($argv[1]); echo$reflect; foreach($reflect>getParameters()as$i=>$param){ printf( "Parameter#%d:%s{\n". "Class:%s\n". "AllowsNULL:%s\n". "Passedtobyreference:%s\n". "Isoptional?:%s\n". "}\n", $i,//$param>getPosition()canbeusedfromPHP5.2.3 $param>getName(), var_export($param>getClass(),1),
ReflectionClass
TheReflectionClassclassletsyoureverseengineerclassesandinterfaces. <?php classReflectionClassimplementsReflector { finalprivate__clone() publicvoid__construct(stringname) publicstring__toString() publicstaticstringexport(mixedclass,boolreturn) publicstringgetName() publicboolisInternal() publicboolisUserDefined() publicboolisInstantiable() publicboolhasConstant(stringname) publicboolhasMethod(stringname) publicboolhasProperty(stringname) publicstringgetFileName() publicintgetStartLine() publicintgetEndLine() publicstringgetDocComment() publicReflectionMethodgetConstructor() publicReflectionMethodgetMethod(stringname) publicReflectionMethod[]getMethods() publicReflectionPropertygetProperty(stringname) publicReflectionProperty[]getProperties() publicarraygetConstants() publicmixedgetConstant(stringname) publicReflectionClass[]getInterfaces() publicboolisInterface() publicboolisAbstract() publicboolisFinal() publicintgetModifiers() publicboolisInstance(stdclassobject) publicstdclassnewInstance(mixedargs) publicstdclassnewInstanceArgs(arrayargs) publicReflectionClassgetParentClass() publicboolisSubclassOf(ReflectionClassclass) publicarraygetStaticProperties() publicmixedgetStaticPropertyValue(stringname[,mixeddefault]) publicvoidsetStaticPropertyValue(stringname,mixedvalue) publicarraygetDefaultProperties() publicboolisIterateable() publicboolimplementsInterface(stringname) publicReflectionExtensiongetExtension() publicstringgetExtensionName() }
?> Note:hasConstant(),hasMethod(),hasProperty(),getStaticPropertyValue()and setStaticPropertyValue()wereaddedinPHP5.1.0,whilenewInstanceArgs()wasaddedin PHP5.1.3. Tointrospectaclass,youwillfirsthavetocreateaninstanceoftheReflectionClassclass.Youcanthencall anyoftheabovemethodsonthisinstance. Example#4UsingtheReflectionClassclass <?php interfaceSerializable { //... } classObject { //... } /** *Acounterclass */ classCounterextendsObjectimplementsSerializable { constSTART=0; privatestatic$c=Counter::START; /** *Invokecounter * *@accesspublic *@returnint */ publicfunctioncount(){ returnself::$c++; } } //CreateaninstanceoftheReflectionClassclass $class=newReflectionClass('Counter'); //Printoutbasicinformation printf( "===>The%s%s%s%s'%s'[extends%s]\n". "declaredin%s\n". "lines%dto%d\n". "havingthemodifiers%d[%s]\n", $class>isInternal()?'internal':'userdefined', $class>isAbstract()?'abstract':'', $class>isFinal()?'final':'', $class>isInterface()?'interface':'class',
$class>getName(), var_export($class>getParentClass(),1), $class>getFileName(), $class>getStartLine(), $class>getEndline(), $class>getModifiers(), implode('',Reflection::getModifierNames($class >getModifiers())) ); //Printdocumentationcomment printf(">Documentation:\n%s\n",var_export($class>getDocComment(), 1)); //Printwhichinterfacesareimplementedbythisclass printf(">Implements:\n%s\n",var_export($class>getInterfaces(), 1)); //Printclassconstants printf(">Constants:%s\n",var_export($class>getConstants(),1)); //Printclassproperties printf(">Properties:%s\n",var_export($class>getProperties(),1)); //Printclassmethods printf(">Methods:%s\n",var_export($class>getMethods(),1)); //Ifthisclassisinstantiable,createaninstance if($class>isInstantiable()){ $counter=$class>newInstance(); echo'>$counterisinstance?'; echo$class>isInstance($counter)?'yes':'no'; echo"\n>newObject()isinstance?"; echo$class>isInstance(newObject())?'yes':'no'; } ?> Note:ThemethodnewInstance()acceptsavariablenumberofargumentswhicharepassedto thefunctionjustasincall_user_func(). Note:$class=newReflectionClass('Foo');$class>isInstance($arg)isequivalentto$arg instanceofFoooris_a($arg,'Foo').
ReflectionObject
TheReflectionObjectclassletsyoureverseengineerobjects. <?php classReflectionObjectextendsReflectionClass { finalprivate__clone()
ReflectionMethod
TheReflectionMethodclassletsyoureverseengineerclassmethods. <?php classReflectionMethodextendsReflectionFunctionAbstractimplementsRefl ector { publicvoid__construct(mixedclass,stringname) publicstring__toString() publicstaticstringexport(mixedclass,stringname,boolreturn) publicmixedinvoke(stdclassobject[,mixedargs[,...]]) publicmixedinvokeArgs(stdclassobject,arrayargs) publicboolisFinal() publicboolisAbstract() publicboolisPublic() publicboolisPrivate() publicboolisProtected() publicboolisStatic() publicboolisConstructor() publicboolisDestructor() publicintgetModifiers() publicmixedgetClosure()/*AsofPHP5.3.0*/ publicReflectionClassgetDeclaringClass() //InheritedfromReflectionFunctionAbstract finalprivate__clone() publicstringgetName() publicboolisInternal() publicboolisUserDefined() publicstringgetFileName() publicintgetStartLine() publicintgetEndLine() publicstringgetDocComment() publicarraygetStaticVariables() publicboolreturnsReference() publicReflectionParameter[]getParameters() publicintgetNumberOfParameters() publicintgetNumberOfRequiredParameters() } ?> Tointrospectamethod,youwillfirsthavetocreateaninstanceoftheReflectionMethodclass.Youcan thencallanyoftheabovemethodsonthisinstance. Example#5UsingtheReflectionMethodclass <?php
classCounter { privatestatic$c=0; /** *Incrementcounter * *@final *@static *@accesspublic *@returnint */ finalpublicstaticfunctionincrement() { return++self::$c; } } //CreateaninstanceoftheReflectionMethodclass $method=newReflectionMethod('Counter','increment'); //Printoutbasicinformation printf( "===>The%s%s%s%s%s%s%smethod'%s'(whichis%s)\n". "declaredin%s\n". "lines%dto%d\n". "havingthemodifiers%d[%s]\n", $method>isInternal()?'internal':'userdefined', $method>isAbstract()?'abstract':'', $method>isFinal()?'final':'', $method>isPublic()?'public':'', $method>isPrivate()?'private':'', $method>isProtected()?'protected':'', $method>isStatic()?'static':'', $method>getName(), $method>isConstructor()?'theconstructor':'aregularmethod ', $method>getFileName(), $method>getStartLine(), $method>getEndline(), $method>getModifiers(), implode('',Reflection::getModifierNames($method >getModifiers())) ); //Printdocumentationcomment printf(">Documentation:\n%s\n",var_export($method>getDocComment(), 1)); //Printstaticvariablesifexistant if($statics=$method>getStaticVariables()){ printf(">Staticvariables:%s\n",var_export($statics,1)); } //Invokethemethod
printf(">Invokationresultsin:"); var_dump($method>invoke(NULL)); ?> Example#6GettingclosureusingReflectionMethodclass <?php classExample{ staticfunctionprinter(){ echo"HelloWorld!\n"; } } $class=newReflectionClass('Example'); $method=$class>getMethod('printer'); $closure=$method>getClosure();/*AsofPHP5.3.0*/ $closure();//HelloWorld! ?> Note:Tryingtoinvokeprivate,protectedorabstractmethodswillresultinanexceptionbeing thrownfromtheinvoke()method. Note:Forstaticmethodsasseenabove,youshouldpassNULLasthefirstargumenttoinvoke(). Fornonstaticmethods,passaninstanceoftheclass.
ReflectionProperty
TheReflectionPropertyclassletsyoureverseengineerclassproperties. <?php classReflectionPropertyimplementsReflector { finalprivate__clone() publicvoid__construct(mixedclass,stringname) publicstring__toString() publicstaticstringexport(mixedclass,stringname,boolreturn) publicstringgetName() publicboolisPublic() publicboolisPrivate() publicboolisProtected() publicboolisStatic() publicboolisDefault() publicvoidsetAccessible()/*AsofPHP5.3.0*/ publicintgetModifiers() publicmixedgetValue(stdclassobject) publicvoidsetValue(stdclassobject,mixedvalue) publicReflectionClassgetDeclaringClass() publicstringgetDocComment() } ?>
Note:getDocComment()wasaddedinPHP5.1.0.setAccessible()wasaddedinPHP5.3.0. Tointrospectaproperty,youwillfirsthavetocreateaninstanceoftheReflectionPropertyclass.Youcan thencallanyoftheabovemethodsonthisinstance. Example#7UsingtheReflectionPropertyclass <?php classString { public$length=5; } //CreateaninstanceoftheReflectionPropertyclass $prop=newReflectionProperty('String','length'); //Printoutbasicinformation printf( "===>The%s%s%s%sproperty'%s'(whichwas%s)\n". "havingthemodifiers%s\n", $prop>isPublic()?'public':'', $prop>isPrivate()?'private':'', $prop>isProtected()?'protected':'', $prop>isStatic()?'static':'', $prop>getName(), $prop>isDefault()?'declaredatcompiletime':'createdatrun time', var_export(Reflection::getModifierNames($prop>getModifiers()), 1) ); //CreateaninstanceofString $obj=newString(); //Getcurrentvalue printf(">Valueis:"); var_dump($prop>getValue($obj)); //Changevalue $prop>setValue($obj,10); printf(">Settingvalueto10,newvalueis:"); var_dump($prop>getValue($obj)); //Dumpobject var_dump($obj); ?> Example#8GettingvaluefromprivateandprotectedpropertiesusingReflectionPropertyclass <?php classFoo{ public$x=1; protected$y=2;
private$z=3; } $obj=newFoo; $prop=newReflectionProperty('Foo','y'); $prop>setAccessible(true);/*AsofPHP5.3.0*/ var_dump($prop>getValue($obj));//int(2) $prop=newReflectionProperty('Foo','z'); $prop>setAccessible(true);/*AsofPHP5.3.0*/ var_dump($prop>getValue($obj));//int(2) ?> Note:Tryingtogetorsetprivateorprotectedclassproperty'svalueswillresultinanexception beingthrown.
ReflectionExtension
TheReflectionExtensionclassletsyoureverseengineerextensions.Youcanretrieveallloadedextensions atruntimeusingtheget_loaded_extensions(). <?php classReflectionExtensionimplementsReflector{ finalprivate__clone() publicvoid__construct(stringname) publicstring__toString() publicstaticstringexport(stringname,boolreturn) publicstringgetName() publicstringgetVersion() publicReflectionFunction[]getFunctions() publicarraygetConstants() publicarraygetINIEntries() publicReflectionClass[]getClasses() publicarraygetClassNames() publicstringinfo() } ?> Tointrospectanextension,youwillfirsthavetocreateaninstanceoftheReflectionExtensionclass.You canthencallanyoftheabovemethodsonthisinstance. Example#9UsingtheReflectionExtensionclass <?php //CreateaninstanceoftheReflectionPropertyclass $ext=newReflectionExtension('standard'); //Printoutbasicinformation printf( "Name:%s\n". "Version:%s\n".
"Functions:[%d]%s\n". "Constants:[%d]%s\n". "INIentries:[%d]%s\n". "Classes:[%d]%s\n", $ext>getName(), $ext>getVersion()?$ext>getVersion():'NO_VERSION', sizeof($ext>getFunctions()), var_export($ext>getFunctions(),1), sizeof($ext>getConstants()), var_export($ext>getConstants(),1), sizeof($ext>getINIEntries()), var_export($ext>getINIEntries(),1), sizeof($ext>getClassNames()), var_export($ext>getClassNames(),1) ); ?>
Extendingthereflectionclasses
Incaseyouwanttocreatespecializedversionsofthebuiltinclasses(say,forcreatingcolorizedHTML whenbeingexported,havingeasyaccessmembervariablesinsteadofmethodsorhavingutilitymethods), youmaygoaheadandextendthem. Example#10Extendingthebuiltinclasses <?php /** *MyReflection_Methodclass */ classMy_Reflection_MethodextendsReflectionMethod { public$visibility=array(); publicfunction__construct($o,$m) { parent::__construct($o,$m); $this>visibility=Reflection::getModifierNames($this >getModifiers()); } } /** *Democlass#1 * */ classT{ protectedfunctionx(){} } /** *Democlass#2
TypeHinting
PHP5introducesTypeHinting.Functionsarenowabletoforceparameterstobeobjects(byspecifyingthe nameoftheclassinthefunctionprototype)orarrays(sincePHP5.1).However,ifNULLisusedasthe defaultparametervalue,itwillbeallowedasanargumentforanylatercall. Example#1TypeHintingexamples <?php //Anexampleclass classMyClass { /** *Atestfunction * *FirstparametermustbeanobjectoftypeOtherClass */ publicfunctiontest(OtherClass$otherclass){ echo$otherclass>var; } /** *Anothertestfunction * *Firstparametermustbeanarray */ publicfunctiontest_array(array$input_array){ print_r($input_array); } } //Anotherexampleclass classOtherClass{ public$var='HelloWorld';
} ?> Failingtosatisfythetypehintresultsinacatchablefatalerror. <?php //Aninstanceofeachclass $myclass=newMyClass; $otherclass=newOtherClass; //FatalError:Argument1mustbeanobjectofclassOtherClass $myclass>test('hello'); //FatalError:Argument1mustbeaninstanceofOtherClass $foo=newstdClass; $myclass>test($foo); //FatalError:Argument1mustnotbenull $myclass>test(null); //Works:PrintsHelloWorld $myclass>test($otherclass); //FatalError:Argument1mustbeanarray $myclass>test_array('astring'); //Works:Printsthearray $myclass>test_array(array('a','b','c')); ?> Typehintingalsoworkswithfunctions: <?php //Anexampleclass classMyClass{ public$var='HelloWorld'; } /** *Atestfunction * *FirstparametermustbeanobjectoftypeMyClass */ functionMyFunction(MyClass$foo){ echo$foo>var; } //Works $myclass=newMyClass; MyFunction($myclass); ?> TypehintingallowingNULLvalue: <?php
LateStaticBindings
AsofPHP5.3.0,PHPimplementsafeaturecalledlatestaticbindingswhichcanbeusedtoreferencethe calledclassinacontextofstaticinheritance. Thisfeaturewasnamed"latestaticbindings"withaninternalperspectiveinmind."Latebinding"comes fromthefactthatstatic::willnolongerberesolvedusingtheclasswherethemethodisdefinedbutitwill ratherbecomputedusingruntimeinformation.Itwasalsocalleda"staticbinding"asitcanbeusedfor(but isnotlimitedto)staticmethodcalls.
Limitationsofself::
Staticreferencestothecurrentclasslikeself::or__CLASS__areresolvedusingtheclassinwhichthe functionbelongs,asinwhereitwasdefined: Example#1self::usage <?php classA{ publicstaticfunctionwho(){ echo__CLASS__; } publicstaticfunctiontest(){ self::who(); } } classBextendsA{ publicstaticfunctionwho(){ echo__CLASS__; } }
LateStaticBindings'usage
Latestaticbindingstriestosolvethatlimitationbyintroducingakeywordthatreferencestheclassthatwas initiallycalledatruntime.Basically,akeywordthatwouldallowyoutoreferenceBfromtest()inthe previousexample.Itwasdecidednottointroduceanewkeywordbutratherusestaticthatwasalready reserved. Example#2static::simpleusage <?php classA{ publicstaticfunctionwho(){ echo__CLASS__; } publicstaticfunctiontest(){ static::who();//HerecomesLateStaticBindings } } classBextendsA{ publicstaticfunctionwho(){ echo__CLASS__; } } B::test(); ?> Theaboveexamplewilloutput:
B
} publicstaticfunctionwho(){ echo__CLASS__."\n"; } } classTestParent{ publicfunction__construct(){ static::who(); } publicstaticfunctionwho(){ echo__CLASS__."\n"; } } $o=newTestChild; $o>test(); ?> Theaboveexamplewilloutput:
TestChild TestParent
Note:Latestaticbindings'resolutionwillstopatafullyresolvedstaticcallwithnofallback.On theotherhand,staticcallsusingkeywordslikeparent::orself::willforwardthecalling information. Example#4Forwardingandnonforwardingcalls <?php classA{ publicstaticfunctionfoo(){ static::who(); } publicstaticfunctionwho(){ echo__CLASS__."\n"; } } classBextendsA{ publicstaticfunctiontest(){ A::foo(); parent::foo(); self::foo(); } publicstaticfunctionwho(){ echo__CLASS__."\n"; } } classCextendsB{
Edgecases
TherearelotsofdifferentwaystotriggeramethodcallinPHP,likecallbacksormagicmethods.Aslate staticbindingsbasetheirresolutiononruntimeinformation,itmightgiveunexpectedresultsinsocalled edgecases. Example#5Latestaticbindingsinsidemagicmethods <?php classA{ protectedstaticfunctionwho(){ echo__CLASS__."\n"; } publicfunction__get($var){ returnstatic::who(); } } classBextendsA{ protectedstaticfunctionwho(){ echo__CLASS__."\n"; } } $b=newB; $b>foo; ?> Theaboveexamplewilloutput:
B
Objectsandreferences
OneofthekeypointofPHP5OOPthatisoftenmentionedisthat"objectsarepassedbyreferencesby default"Thisisnotcompletelytrue.Thissectionrectifiesthatgeneralthoughtusingsomeexamples. APHPreferenceisanalias,whichallowstwodifferentvariablestowritetothesamevalue.AsofPHP5,an objectvariabledoesn'tcontaintheobjectitselfasvalueanymore.Itonlycontainsaobjectidentifierwhich allowsobjectaccessorstofindtheactualobject.Whenanobjectissentbyargument,returnedorassignedto anothervariable,thedifferentvariablesarenotaliases:theyholdacopyoftheidentifier,whichpointstothe sameobject. Example#1ReferencesandObjects <?php classA{ public$foo=1; } $a=newA; $b=$a;//$aand$barecopiesofthesameidentifier //($a)=($b)=<id> $b>foo=2; echo$a>foo."\n"; $c=newA; $d=&$c;//$cand$darereferences //($c,$d)=<id> $d>foo=2; echo$c>foo."\n"; $e=newA; functionfoo($obj){ //($obj)=($e)=<id> $obj>foo=2; } foo($e); echo$e>foo."\n"; ?> Theaboveexamplewilloutput:
2 2 2
Namespaces
TableofContents
Namespacesoverview
NamespacesinPHParedesignedtosolvescopingprobleminlargePHPlibraries.InPHP,allclass definitionsareglobal.Thus,whenalibraryauthorcreatesvariousutilityorpublicAPIclassesforthelibrary, hemustbeawareofthepossibilitythatotherlibrarieswithsimilarfunctionalitywouldexistandthuschoose uniquenamessothattheselibrariescouldbeusedtogether.Usuallyitissolvedbyprefixingtheclassnames withanuniquestringe.g.,databaseclasseswouldhaveprefixMy_Library_DB,etc.Asthelibrarygrows, prefixesaddup,leadingtotheverylongnames. Thenamespacesallowthedevelopertomanagenamingscopeswithoutusingthelongnameseachtimethe classisreferredto,andsolvetheproblemofsharedglobalsspacewithoutmakingcodeunreadable. NamespacesareavailableinPHPasofPHP5.3.0.Thissectionisexperimentalandsubjecttochanges.
Namespacedefinition
Thenamespaceisdeclaredusingnamespacekeyword,whichshouldbeattheverybeginningofthefile. Example: Example#1Definingnamespace <?php namespaceMyProject::DB; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} ?> Samenamespacenamecanbeusedinmultiplefiles.
Namespacecancontainclass,constantandfunctiondefinitions,butnofreecode. Namespacedefinitiondoesthefollowing:
Insidenamespace,allclass,functionandconstantnamesindefinitionsareautomaticallyprefixed withnamespacename.Theclassnameisalwaysthefullname,i.e.intheexampleabovetheclassis calledMyProject::DB::Connection. Constantdefinitionscreateconstantwhichiscomposedofnamespacenameandconstantname.Like classconstants,namespaceconstantcanonlycontainsstaticvalues. Unqualifiedclassname(i.e.,namenotcontaining::)isresolvedatruntimefollowingthisprocedure: 1. Classislookedupinsidethecurrentnamespace(i.e.prefixingthenamewiththecurrent namespacename)withoutattemptingtoautoload. 2. Classislookedupinsidetheglobalnamespacewithoutattemptingtoautoload. 3. Autoloadingfornameincurrentnamespaceisattempted. 4. Ifpreviousfailed,lookupfails. Unqualifiedfunctionname(i.e.,namenotcontaining::)islookedupatruntimefirstinthecurrent namespaceandthenintheglobalspace. Unqualifiedconstantnamesarelookedupfirstatcurrentnamespaceandthenamonggloballydefined constants.
Seealsothefullnameresolutionrules.
Usingnamespaces
Everyclassandfunctioninanamespacecanbereferredtobythefullnamee.g. MyProject::DB::ConnectionorMyProject::DB::connectatanytime. Example#1Usingnamespacedname <?php require'MyProject/Db/Connection.php'; $x=newMyProject::DB::Connection; MyProject::DB::connect(); ?> Namespacescanbeimportedintocurrentcontext(globalornamespace)usingtheuseoperator.Thesyntax fortheoperatoris: <?php /*...*/ useSome::NameasOthername; //Thesimplifiedformofuse: useFoo::Bar; //whichisthesameas: useFoo::BarasBar;
?> Theimportednameworksasfollows:everytimethatthecompilerencountersthelocalnameOthername(as standalonenameorasprefixtothelongernameseparatedby::)theimportednameSome::Nameis substitutedinstead. usecanbeusedonlyinglobalscope,notinsidefunctionorclass.Importednameshaveeffectfromthepoint ofimporttotheendofthecurrentfile.Itisrecommendedtoputimportsatthebeginningofthefiletoavoid confusion. Example#2Importingandaccessingnamespace <?php require'MyProject/Db/Connection.php'; useMyProject::DB; useMyProject::DB::ConnectionasDbConnection; $x=newMyProject::DB::Connection(); $y=newDB::connection(); $z=newDbConnection(); DB::connect(); ?> Note:Theimportoperationiscompiletimeonly,alllocalnamesareconvertedtotheirfull equivalentsbythecompiler.Notethatitwon'ttranslatenamesinstrings,socallbackscan'trely onimportrules.
Globalspace
Withoutanynamespacedefinition,allclassandfunctiondefinitionsareplacedintotheglobalspaceasit wasinPHPbeforenamespacesweresupported.Prefixinganamewith::willspecifythatthenameis requiredfromtheglobalspaceeveninthecontextofthenamespace. Example#1Usingglobalspacespecification <?php namespaceA::B::C; /*ThisfunctionisA::B::C::fopen*/ functionfopen(){ /*...*/ $f=::fopen(...);//callglobalfopen return$f; } ?>
__NAMESPACE__
Thecompiletimeconstant__NAMESPACE__isdefinedtothenameofthecurrentnamespace.Outside namespacethisconstanthasthevalueofemptystring.Thisconstantisusefulwhenoneneedstocompose fullnameforlocalnamespacednames. Example#1Using__NAMESPACE__ <?php namespaceA::B::C; functionfoo(){ //dostuff } set_error_handler(__NAMESPACE__."::foo"); ?>
Nameresolutionrules
Namesareresolvedfollowingtheseresolutionrules: 1. Allqualifiednamesaretranslatedduringcompilationaccordingtocurrentimportrules.Inexample,if thenamespaceA::B::Cisimported,acalltoC::D::e()istranslatedtoA::B::C::D::e(). 2. Unqualifiedclassnamesaretranslatedduringcompilationaccordingtocurrentimportrules(full namesubstitutedforshortimportedname).Inexample,ifthenamespaceA::B::Cisimported,new C()istranslatedtonewA::B::C(). 3. Insidenamespace,callstounqualifiedfunctionsthataredefinedinthecurrentnamespace(andare knownatthetimethecallisparsed)areinterpretedascallstothesenamespacefunctions,atcompile time. 4. Insidenamespace(sayA::B),callstounqualifiedfunctionsthatarenotdefinedincurrentnamespace areresolvedatruntime.Hereishowacalltofunctionfoo()isresolved: 1. Itlooksforafunctionfromthecurrentnamespace:A::B::foo(). 2. Ittriestofindandcalltheinternalfunctionfoo(). Tocallauserdefinedfunctionintheglobalnamespace,::foo()hastobeused. 5. Insidenamespace(sayA::B),callstounqualifiedclassnamesareresolvedatruntime.Hereishowa calltonewC()isresolved: 1. Itlooksforaclassfromthecurrentnamespace:A::B::C. 2. IttriestofindandcalltheinternalclassC. 3. ItattemtstoautoloadA::B::C. Toreferenceauserdefinedclassintheglobalnamespace,new::C()hastobeused. 6. Callstoqualifiedfunctionsareresolvedatruntime.HereishowacalltoA::B::foo()isresolved: 1. Itlooksforafunctionfoo()inthenamespaceA::B. 2. ItlooksforaclassA::Bandcallitsstaticmethodfoo().Itwillautoloadtheclassifnecessary. 7. Qualifiedclassnamesareresolvedincompiletimeasclassfromcorrespondingnamespace.For example,newA::B::C()referstoclassCfromnamespaceA::B.
Example#1Nameresolutionsillustrated <?php namespaceA; //functioncalls foo();//firsttriestocall"foo"definedinnamespace"A" //thencallsinternalfunction"foo" ::foo();//callsfunction"foo"definedinglobalscope //classreferences newB();//firsttriestocreateobjectofclass"B"definedinnames pace"A" //thencreatesobjectofinternalclass"B" new::B();//createsobjectofclass"B"definedinglobalscope //staticmethods/namespacefunctionsfromanothernamespace B::foo();//firsttriestocallfunction"foo"fromnamespace"A::B" //thencallsmethod"foo"ofinternalclass"B" ::B::foo();//firsttriestocallfunction"foo"fromnamespace"B" //thencallsmethod"foo"ofclass"B"fromglobalscope //staticmethods/namespacefunctionsofcurrentnamespace A::foo();//firsttriestocallfunction"foo"fromnamespace"A::A" //thentriestocallmethod"foo"ofclass"A"fromnamespac e"A" //thentriestocallfunction"foo"fromnamespace"A" //thencallsmethod"foo"ofinternalclass"A" ::A::foo();//firsttriestocallfunction"foo"fromnamespace"A" //thencallsmethod"foo"ofclass"A"fromglobalscope ?>
Exceptions
PHP5hasanexceptionmodelsimilartothatofotherprogramminglanguages.Anexceptioncanbethrown, andcaught("catched")withinPHP.Codemaybesurroundedinatryblock,tofacilitatethecatchingof potentialexceptions.Eachtrymusthaveatleastonecorrespondingcatchblock.Multiplecatchblockscanbe usedtocatchdifferentclassesofexeptions.Normalexecution(whennoexceptionisthrownwithinthetry block,orwhenacatchmatchingthethrownexception'sclassisnotpresent)willcontinueafterthatlastcatch blockdefinedinsequence.Exceptionscanbethrown(orrethrown)withinacatchblock.
Whenanexceptionisthrown,codefollowingthestatementwillnotbeexecuted,andPHPwillattemptto findthefirstmatchingcatchblock.Ifanexceptionisnotcaught,aPHPFatalErrorwillbeissuedwithan "UncaughtException..."message,unlessahandlerhasbeendefinedwithset_exception_handler(). Example#1ThrowinganException <?php functioninverse($x){ if(!$x){ thrownewException('Divisionbyzero.'); } elsereturn1/$x; } try{ echoinverse(5)."\n"; echoinverse(0)."\n"; }catch(Exception$e){ echo'Caughtexception:',$e>getMessage(),"\n"; } //Continueexecution echo'HelloWorld'; ?> Theaboveexamplewilloutput:
0.2 Caughtexception:Divisionbyzero. HelloWorld
Example#2NestedException <?php classMyExceptionextendsException{} classTest{ publicfunctiontesting(){ try{ try{ thrownewMyException('foo!'); }catch(MyException$e){ /*rethrowit*/ throw$e; } }catch(Exception$e){ var_dump($e>getMessage()); } } } $foo=newTest; $foo>testing();
?> Theaboveexamplewilloutput:
string(4)"foo!"
ExtendingExceptions
AUserdefinedExceptionclasscanbedefinedbyextendingthebuiltinExceptionclass.Themembersand propertiesbelow,showwhatisaccessiblewithinthechildclassthatderivesfromthebuiltinException class. Example#3TheBuiltinExceptionclass <?php classException { protected$message='Unknownexception';//exceptionmessage protected$code=0;//userdefinedexception code protected$file;//sourcefilenameofexc eption protected$line;//sourcelineofexcepti on function__construct($message=null,$code=0); finalfunctiongetMessage();//messageofexception finalfunctiongetCode();//codeofexception finalfunctiongetFile();//sourcefilename finalfunctiongetLine();//sourceline finalfunctiongetTrace();//anarrayofthebacktr ace() finalfunctiongetTraceAsString();//formatedstringoftra ce /*Overrideable*/ function__toString();//formatedstringford isplay } ?> IfaclassextendsthebuiltinExceptionclassandredefinestheconstructor,itishighlyrecomendedthatit alsocallparent::__construct()toensureallavailabledatahasbeenproperlyassigned.The__toString() methodcanbeoverridentoprovideacustomoutputwhentheobjectispresentedasastring. Example#4ExtendingtheExceptionclass <?php /** *Defineacustomexceptionclass */
classMyExceptionextendsException { //Redefinetheexceptionsomessageisn'toptional publicfunction__construct($message,$code=0){ //somecode //makesureeverythingisassignedproperly parent::__construct($message,$code); } //customstringrepresentationofobject publicfunction__toString(){ return__CLASS__.":[{$this>code}]:{$this>message}\n"; } publicfunctioncustomFunction(){ echo"ACustomfunctionforthistypeofexception\n"; } } /** *Createaclasstotesttheexception */ classTestException { public$var; constTHROW_NONE=0; constTHROW_CUSTOM=1; constTHROW_DEFAULT=2; function__construct($avalue=self::THROW_NONE){ switch($avalue){ caseself::THROW_CUSTOM: //throwcustomexception thrownewMyException('1isaninvalidparameter',5); break; caseself::THROW_DEFAULT: //throwdefaultone. thrownewException('2isntallowedasaparameter',6); break; default: //Noexception,objectwillbecreated. $this>var=$avalue; break; } } } //Example1
try{ $o=newTestException(TestException::THROW_CUSTOM); }catch(MyException$e){//Willbecaught echo"Caughtmyexception\n",$e; $e>customFunction(); }catch(Exception$e){//Skipped echo"CaughtDefaultException\n",$e; } //Continueexecution var_dump($o); echo"\n\n"; //Example2 try{ $o=newTestException(TestException::THROW_DEFAULT); }catch(MyException$e){//Doesn'tmatchthistype echo"Caughtmyexception\n",$e; $e>customFunction(); }catch(Exception$e){//Willbecaught echo"CaughtDefaultException\n",$e; } //Continueexecution var_dump($o); echo"\n\n"; //Example3 try{ $o=newTestException(TestException::THROW_CUSTOM); }catch(Exception$e){//Willbecaught echo"DefaultExceptioncaught\n",$e; } //Continueexecution var_dump($o); echo"\n\n"; //Example4 try{ $o=newTestException(); }catch(Exception$e){//Skipped,noexception echo"DefaultExceptioncaught\n",$e; } //Continueexecution var_dump($o); echo"\n\n"; ?>
ReferencesExplained
TableofContents
WhatReferencesAre
ReferencesinPHPareameanstoaccessthesamevariablecontentbydifferentnames.TheyarenotlikeC pointers;instead,theyaresymboltablealiases.NotethatinPHP,variablenameandvariablecontentare different,sothesamecontentcanhavedifferentnames.ThemostcloseanalogyiswithUnixfilenamesand filesvariablenamesaredirectoryentries,whilevariablecontentsisthefileitself.Referencescanbethought ofashardlinkinginUnixfilesystem.
WhatReferencesDo
PHPreferencesallowyoutomaketwovariablestorefertothesamecontent.Meaning,whenyoudo: <?php $a=&$b; ?> itmeansthat$aand$bpointtothesamecontent. Note:$aand$barecompletelyequalhere,that'snot$aispointingto$borviceversa,that's$a and$bpointingtothesameplace. Note:Ifarraywithreferencesiscopied,itsvaluesarenotdereferenced.Thisisvalidalsofor arrayspassedbyvaluetofunctions. Note:Ifyouassign,passorreturnanundefinedvariablebyreference,itwillgetcreated. Example#1Usingreferenceswithundefinedvariables <?php functionfoo(&$var){} foo($a);//$ais"created"andassignedtonull $b=array(); foo($b['b']);
var_dump(array_key_exists('b',$b));//bool(true) $c=newStdClass; foo($c>d); var_dump(property_exists($c,'d'));//bool(true) ?> Thesamesyntaxcanbeusedwithfunctions,thatreturnreferences,andwithnewoperator(inPHP4.0.4and later): <?php $bar=&newfooclass(); $foo=&find_var($bar); ?> SincePHP5,newreturnreferenceautomaticallysousing=&inthiscontextisdeprecatedandproduces E_STRICTlevelmessage. Note:Notusingthe&operatorcausesacopyoftheobjecttobemade.Ifyouuse$thisinthe classitwilloperateonthecurrentinstanceoftheclass.Theassignmentwithout&willcopythe instance(i.e.theobject)and$thiswilloperateonthecopy,whichisnotalwayswhatisdesired. Usuallyyouwanttohaveasingleinstancetoworkwith,duetoperformanceandmemory consumptionissues. Whileyoucanusethe@operatortomuteanyerrorsintheconstructorwhenusingitas@new, thisdoesnotworkwhenusingthe&newstatement.ThisisalimitationoftheZendEngineand willthereforeresultinaparsererror. Warning Ifyouassignareferencetoavariabledeclaredglobalinsideafunction,thereferencewillbevisibleonly insidethefunction.Youcanavoidthisbyusingthe$GLOBALSarray. Example#2Referencingglobalvariablesinsidefunction <?php $var1="Examplevariable"; $var2=""; functionglobal_references($use_globals) { global$var1,$var2; if(!$use_globals){ $var2=&$var1;//visibleonlyinsidethefunction }else{ $GLOBALS["var2"]=&$var1;//visiblealsoinglobalcontext } } global_references(false); echo"var2issetto'$var2'\n";//var2issetto'' global_references(true); echo"var2issetto'$var2'\n";//var2issetto'Examplevariable' ?> Thinkaboutglobal$var;asashortcutto$var=&$GLOBALS['var'];.Thusassigningotherreferenceto
$varonlychangesthelocalvariable'sreference. Note:Ifyouassignavaluetoavariablewithreferencesinaforeachstatement,thereferencesare modifiedtoo. Example#3Referencesandforeachstatement <?php $ref=0; $row=&$ref; foreach(array(1,2,3)as$row){ //dosomething } echo$ref;//3lastelementoftheiteratedarray ?> Thesecondthingreferencesdoistopassvariablesbyreference.Thisisdonebymakingalocalvariableina functionandavariableinthecallingscopereferencetothesamecontent.Example: <?php functionfoo(&$var) { $var++; } $a=5; foo($a); ?> willmake$atobe6.Thishappensbecauseinthefunctionfoothevariable$varreferstothesamecontentas $a.Seealsomoredetailedexplanationsaboutpassingbyreference. Thethirdthingreferencecandoisreturnbyreference.
WhatReferencesAreNot
Assaidbefore,referencesaren'tpointers.Thatmeans,thefollowingconstructwon'tdowhatyouexpect: <?php functionfoo(&$var) { $var=&$GLOBALS["baz"]; } foo($bar); ?> Whathappensisthat$varinfoowillbeboundwith$barincaller,butthenitwillbereboundwith $GLOBALS["baz"].There'snowaytobind$barinthecallingscopetosomethingelseusingthereference mechanism,since$barisnotavailableinthefunctionfoo(itisrepresentedby$var,but$varhasonly variablecontentsandnotnametovaluebindinginthecallingsymboltable).Youcanusereturning
referencestoreferencevariablesselectedbythefunction.
PassingbyReference
Youcanpassvariabletofunctionbyreference,sothatfunctioncouldmodifyitsarguments.Thesyntaxisas follows: <?php functionfoo(&$var) { $var++; } $a=5; foo($a); //$ais6here ?> Notethatthere'snoreferencesignonfunctioncallonlyonfunctiondefinition.Functiondefinitionaloneis enoughtocorrectlypasstheargumentbyreference.InrecentversionsofPHPyouwillgetawarningsaying that"Calltimepassbyreference"isdeprecatedwhenyouusea&infoo(&$a);. Thefollowingthingscanbepassedbyreference:
Variable,i.e.foo($a) Newstatement,i.e.foo(newfoobar()) Reference,returnedfromafunction,i.e.: <?php function&bar() { $a=5; return$a; } foo(bar()); ?> Seealsoexplanationsaboutreturningbyreference.
Anyotherexpressionshouldnotbepassedbyreference,astheresultisundefined.Forexample,the followingexamplesofpassingbyreferenceareinvalid: <?php functionbar()//Notethemissing& { $a=5; return$a; } foo(bar());//ProducesfatalerrorsincePHP5.0.5 foo($a=5);//Expression,notvariable foo(5);//Producesfatalerror ?> TheserequirementsareforPHP4.0.4andlater.
ReturningReferences
Returningbyreferenceisusefulwhenyouwanttouseafunctiontofindwhichvariableareferenceshould beboundto.Donotusereturnbyreferencetoincreaseperformance,theengineissmartenoughtooptimize thisonitsown.Onlyreturnreferenceswhenyouhaveavalidtechnicalreasontodoit!Toreturnreferences, usethissyntax: <?php classfoo{ public$value=42; publicfunction&getValue(){ return$this>value; } } $obj=newfoo; $myValue=&$obj>getValue();//$myValueisareferenceto$obj>value, whichis42. $obj>value=2; echo$myValue;//printsthenewvalueof$obj>value,i.e .2. ?> Inthisexample,thepropertyoftheobjectreturnedbythegetValuefunctionwouldbeset,notthecopy,asit wouldbewithoutusingreferencesyntax. Note:Unlikeparameterpassing,hereyouhavetouse&inbothplacestoindicatethatyou returnbyreference,notacopyasusual,andtoindicatethatreferencebinding,ratherthanusual assignment,shouldbedonefor$myValue. Note:Ifyoutrytoreturnareferencefromafunctionwiththesyntax:return($this>value);this willnotworkasyouareattemptingtoreturntheresultofanexpression,andnotavariable,by reference.Youcanonlyreturnvariablesbyreferencefromafunctionnothingelse.E_NOTICE errorisissuedsincePHP4.4.0andPHP5.1.0ifthecodetriestoreturnadynamicexpressionora resultofthenewoperator.
UnsettingReferences
Whenyouunsetthereference,youjustbreakthebindingbetweenvariablenameandvariablecontent.This doesnotmeanthatvariablecontentwillbedestroyed.Forexample: <?php $a=1; $b=&$a; unset($a);
SpottingReferences
ManysyntaxconstructsinPHPareimplementedviareferencingmechanisms,soeverythingtoldaboveabout referencebindingalsoapplytotheseconstructs.Someconstructs,likepassingandreturningbyreference, arementionedabove.Otherconstructsthatusereferencesare:
globalReferences
Whenyoudeclarevariableasglobal$varyouareinfactcreatingreferencetoaglobalvariable.Thatmeans, thisisthesameas: <?php $var=&$GLOBALS["var"]; ?> Thatmeans,forexample,thatunsetting$varwon'tunsetglobalvariable.
$this
Inanobjectmethod,$thisisalwaysareferencetothecallerobject.
Predefinedvariables
PHPprovidesalargenumberofpredefinedvariablestoallscripts.Thevariablesrepresenteverythingfrom externalvariablestobuiltinenvironmentvariables,lasterrormessagestolastretrievedheaders. SeealsotheFAQtitled"Howdoesregister_globalsaffectme?"
Superglobals
SuperglobalsSuperglobalsarebuiltinvariablesthatarealwaysavailableinallscopes
Description
SeveralpredefinedvariablesinPHPare"superglobals",whichmeanstheyareavailableinallscopes throughoutascript.Thereisnoneedtodoglobal$variable;toaccessthemwithinfunctionsormethods. Thesesuperglobalvariablesare:
ChangeLog
Version 4.1.0 Description SuperglobalswereintroducedtoPHP.
Notes
Note:Variableavailability Bydefault,allofthesuperglobalsareavailablebuttherearedirectivesthataffectthis availability.Forfurtherinformation,refertothedocumentationforvariables_order. Note:Dealingwithregister_globals Ifthedeprecatedregister_globalsdirectiveissettoonthenthevariableswithinwillalsobemade availableintheglobalscopeofthescript.Forexample,$_POST['foo']wouldalsoexistas$foo. Forrelatedinformation,seetheFAQtitled"Howdoesregister_globalsaffectme?" Note:Variablevariables Superglobalscannotbeusedasvariablevariablesinsidefunctionsorclassmethods.
SeeAlso
variablescope
Thevariables_orderdirective Thefilterextension
$GLOBALS
$GLOBALSReferencesallvariablesavailableinglobalscope
Description
Anassociativearraycontainingreferencestoallvariableswhicharecurrentlydefinedintheglobalscopeof thescript.Thevariablenamesarethekeysofthearray.
Examples
Example#1$GLOBALSexample <?php functiontest(){ $foo="localvariable"; echo'$fooinglobalscope:'.$GLOBALS["foo"]."\n"; echo'$fooincurrentscope:'.$foo."\n"; } $foo="Examplecontent"; test(); ?> Theaboveexamplewilloutputsomethingsimilarto:
$fooinglobalscope:Examplecontent $fooincurrentscope:localvariable
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods. Note:Variableavailability Unlikealloftheothersuperglobals,$GLOBALShasessentiallyalwaysbeenavailableinPHP.
$_SERVER $HTTP_SERVER_VARS[deprecated]
$_SERVER$HTTP_SERVER_VARS[deprecated]Serverandexecutionenvironmentinformation
Description
$_SERVERisanarraycontaininginformationsuchasheaders,paths,andscriptlocations.Theentriesinthis arrayarecreatedbythewebserver.Thereisnoguaranteethateverywebserverwillprovideanyofthese; serversmayomitsome,orprovideothersnotlistedhere.Thatsaid,alargenumberofthesevariablesare accountedforintheCGI1.1specification,soyoushouldbeabletoexpectthose. $HTTP_SERVER_VARScontainsthesameinitialinformation,butisnotasuperglobal.(Notethat $HTTP_SERVER_VARSand$_SERVERaredifferentvariablesandthatPHPhandlesthemassuch) Youmayormaynotfindanyofthefollowingelementsin$_SERVER.Notethatfew,ifany,ofthesewillbe available(orindeedhaveanymeaning)ifrunningPHPonthecommandline. 'PHP_SELF' Thefilenameofthecurrentlyexecutingscript,relativetothedocumentroot.Forinstance, $_SERVER['PHP_SELF']inascriptattheaddresshttp://example.com/test.php/foo.barwouldbe /test.php/foo.bar.The__FILE__constantcontainsthefullpathandfilenameofthecurrent(i.e. included)file.IfPHPisrunningasacommandlineprocessorthisvariablecontainsthescriptname sincePHP4.3.0.Previouslyitwasnotavailable. 'argv' Arrayofargumentspassedtothescript.Whenthescriptisrunonthecommandline,thisgivesCstyle accesstothecommandlineparameters.WhencalledviatheGETmethod,thiswillcontainthequery string. 'argc' Containsthenumberofcommandlineparameterspassedtothescript(ifrunonthecommandline). 'GATEWAY_INTERFACE' WhatrevisionoftheCGIspecificationtheserverisusing;i.e.'CGI/1.1'. 'SERVER_ADDR' TheIPaddressoftheserverunderwhichthecurrentscriptisexecuting. 'SERVER_NAME' Thenameoftheserverhostunderwhichthecurrentscriptisexecuting.Ifthescriptisrunningona virtualhost,thiswillbethevaluedefinedforthatvirtualhost. 'SERVER_SOFTWARE' Serveridentificationstring,givenintheheaderswhenrespondingtorequests. 'SERVER_PROTOCOL' Nameandrevisionoftheinformationprotocolviawhichthepagewasrequested;i.e.'HTTP/1.0'; 'REQUEST_METHOD' Whichrequestmethodwasusedtoaccessthepage;i.e.'GET','HEAD','POST','PUT'.
Note:PHPscriptisterminatedaftersendingheaders(itmeansafterproducinganyoutput withoutoutputbuffering)iftherequestmethodwasHEAD. 'REQUEST_TIME' Thetimestampofthestartoftherequest.AvailablesincePHP5.1.0. 'QUERY_STRING' Thequerystring,ifany,viawhichthepagewasaccessed. 'DOCUMENT_ROOT' Thedocumentrootdirectoryunderwhichthecurrentscriptisexecuting,asdefinedintheserver's configurationfile. 'HTTP_ACCEPT' ContentsoftheAccept:headerfromthecurrentrequest,ifthereisone. 'HTTP_ACCEPT_CHARSET' ContentsoftheAcceptCharset:headerfromthecurrentrequest,ifthereisone.Example: 'iso88591,*,utf8'. 'HTTP_ACCEPT_ENCODING' ContentsoftheAcceptEncoding:headerfromthecurrentrequest,ifthereisone.Example:'gzip'. 'HTTP_ACCEPT_LANGUAGE' ContentsoftheAcceptLanguage:headerfromthecurrentrequest,ifthereisone.Example:'en'. 'HTTP_CONNECTION' ContentsoftheConnection:headerfromthecurrentrequest,ifthereisone.Example:'KeepAlive'. 'HTTP_HOST' ContentsoftheHost:headerfromthecurrentrequest,ifthereisone. 'HTTP_REFERER' Theaddressofthepage(ifany)whichreferredtheuseragenttothecurrentpage.Thisissetbytheuser agent.Notalluseragentswillsetthis,andsomeprovidetheabilitytomodifyHTTP_REFERERasa feature.Inshort,itcannotreallybetrusted. 'HTTP_USER_AGENT' ContentsoftheUserAgent:headerfromthecurrentrequest,ifthereisone.Thisisastringdenoting theuseragentbeingwhichisaccessingthepage.Atypicalexampleis:Mozilla/4.5[en](X11;U; Linux2.2.9i586).Amongotherthings,youcanusethisvaluewithget_browser()totailoryourpage's outputtothecapabilitiesoftheuseragent. 'HTTPS' SettoanonemptyvalueifthescriptwasqueriedthroughtheHTTPSprotocol.Notethatwhenusing ISAPIwithIIS,thevaluewillbeoffiftherequestwasnotmadethroughtheHTTPSprotocol. 'REMOTE_ADDR' TheIPaddressfromwhichtheuserisviewingthecurrentpage. 'REMOTE_HOST' TheHostnamefromwhichtheuserisviewingthecurrentpage.Thereversednslookupisbasedoff theREMOTE_ADDRoftheuser. Note:Yourwebservermustbeconfiguredtocreatethisvariable.ForexampleinApache you'llneedHostnameLookupsOninsidehttpd.confforittoexist.Seealsogethostbyaddr(). 'REMOTE_PORT' Theportbeingusedontheuser'smachinetocommunicatewiththewebserver. 'SCRIPT_FILENAME' Theabsolutepathnameofthecurrentlyexecutingscript.
Note:IfascriptisexecutedwiththeCLI,asarelativepath,suchasfile.phpor../file.php, $_SERVER['SCRIPT_FILENAME']willcontaintherelativepathspecifiedbytheuser. 'SERVER_ADMIN' ThevaluegiventotheSERVER_ADMIN(forApache)directiveinthewebserverconfigurationfile.If thescriptisrunningonavirtualhost,thiswillbethevaluedefinedforthatvirtualhost. 'SERVER_PORT' Theportontheservermachinebeingusedbythewebserverforcommunication.Fordefaultsetups, thiswillbe'80';usingSSL,forinstance,willchangethistowhateveryourdefinedsecureHTTPport is. 'SERVER_SIGNATURE' Stringcontainingtheserverversionandvirtualhostnamewhichareaddedtoservergeneratedpages,if enabled. 'PATH_TRANSLATED' Filesystem(notdocumentroot)basedpathtothecurrentscript,aftertheserverhasdoneanyvirtual torealmapping. Note:AsofPHP4.3.2,PATH_TRANSLATEDisnolongersetimplicitlyunderthe Apache2SAPIincontrasttothesituationinApache1,whereit'ssettothesamevalueas theSCRIPT_FILENAMEservervariablewhenit'snotpopulatedbyApache.Thischange wasmadetocomplywiththeCGIspecificationthatPATH_TRANSLATEDshouldonly existifPATH_INFOisdefined.Apache2usersmayuseAcceptPathInfo=Oninside httpd.conftodefinePATH_INFO. 'SCRIPT_NAME' Containsthecurrentscript'spath.Thisisusefulforpageswhichneedtopointtothemselves.The __FILE__constantcontainsthefullpathandfilenameofthecurrent(i.e.included)file. 'REQUEST_URI' TheURIwhichwasgiveninordertoaccessthispage;forinstance,'/index.html'. 'PHP_AUTH_DIGEST' WhenrunningunderApacheasmoduledoingDigestHTTPauthenticationthisvariableissettothe 'Authorization'headersentbytheclient(whichyoushouldthenusetomaketheappropriate validation). 'PHP_AUTH_USER' WhenrunningunderApacheorIIS(ISAPIonPHP5)asmoduledoingHTTPauthenticationthis variableissettotheusernameprovidedbytheuser. 'PHP_AUTH_PW' WhenrunningunderApacheorIIS(ISAPIonPHP5)asmoduledoingHTTPauthenticationthis variableissettothepasswordprovidedbytheuser. 'AUTH_TYPE' WhenrunningunderApacheasmoduledoingHTTPauthenticatedthisvariableissettothe authenticationtype.
ChangeLog
Version 4.1.0 Description Introduced$_SERVERthatthedeprecated$HTTP_SERVER_VARS.
Examples
Example#1$_SERVERexample <?php echo$_SERVER['SERVER_NAME']; ?> Theaboveexamplewilloutputsomethingsimilarto:
www.example.com
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods.
SeeAlso
Thefilterextension
$_GET $HTTP_GET_VARS[deprecated]
$_GET$HTTP_GET_VARS[deprecated]HTTPGETvariables
Description
AnassociativearrayofvariablespassedtothecurrentscriptviatheHTTPGETmethod. $HTTP_GET_VARScontainsthesameinitialinformation,butisnotasuperglobal.(Notethat $HTTP_GET_VARSand$_GETaredifferentvariablesandthatPHPhandlesthemassuch)
ChangeLog
Version 4.1.0 Description Introduced$_GETthatdeprecated$HTTP_GET_VARS.
Examples
Example#1$_GETexample <?php echo'Hello'.htmlspecialchars($_GET["name"]).'!'; ?> Assumingtheuserenteredhttp://example.com/?name=Hannes Theaboveexamplewilloutputsomethingsimilarto:
HelloHannes!
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods.
SeeAlso
Handlingexternalvariables Thefilterextension
$_POST $HTTP_POST_VARS[deprecated]
$_POST$HTTP_POST_VARS[deprecated]HTTPPOSTvariables
Description
AnassociativearrayofvariablespassedtothecurrentscriptviatheHTTPPOSTmethod. $HTTP_POST_VARScontainsthesameinitialinformation,butisnotasuperglobal.(Notethat $HTTP_POST_VARSand$_POSTaredifferentvariablesandthatPHPhandlesthemassuch)
ChangeLog
Version 4.1.0 Description Introduced$_POSTthatdeprecated$HTTP_POST_VARS.
Examples
Example#1$_POSTexample <?php echo'Hello'.htmlspecialchars($_POST["name"]).'!'; ?> AssumingtheuserPOSTedname=Hannes Theaboveexamplewilloutputsomethingsimilarto:
HelloHannes!
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods.
SeeAlso
Handlingexternalvariables Thefilterextension
$_FILES $HTTP_POST_FILES[deprecated]
$_FILES$HTTP_POST_FILES[deprecated]HTTPFileUploadvariables
Description
AnassociativearrayofitemsuploadedtothecurrentscriptviatheHTTPPOSTmethod. $HTTP_POST_FILEScontainsthesameinitialinformation,butisnotasuperglobal.(Notethat $HTTP_POST_FILESand$_FILESaredifferentvariablesandthatPHPhandlesthemassuch)
ChangeLog
Version 4.1.0 Description Introduced$_FILESthatdeprecated$HTTP_POST_FILES.
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods.
SeeAlso
move_uploaded_file() HandlingFileUploads
$_REQUEST
$_REQUESTHTTPRequestvariables
Description
Anassociativearraythatbydefaultcontainsthecontentsof$_GET,$_POSTand$_COOKIE.
ChangeLog
Version 5.3.0 4.3.0 4.1.0 Description Introducedrequest_order.Thisdirectiveaffectsthecontentsof$_REQUEST. $_FILESinformationwasremovedfrom$_REQUEST. Introduced$_REQUEST.
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods. Note:Whenrunningonthecommandline,thiswillnotincludetheargvandargcentries;these arepresentinthe$_SERVERarray. Note:VariablesprovidedtothescriptviatheGET,POST,andCOOKIEinputmechanisms,and whichthereforecannotbetrusted.Thepresenceandorderofvariableinclusioninthisarrayis definedaccordingtothePHPvariables_orderconfigurationdirective.
SeeAlso
$_SESSION $HTTP_SESSION_VARS[deprecated]
$_SESSION$HTTP_SESSION_VARS[deprecated]Sessionvariables
Description
Anassociativearraycontainingsessionvariablesavailabletothecurrentscript.SeetheSessionfunctions documentationformoreinformationonhowthisisused. $HTTP_SESSION_VARScontainsthesameinitialinformation,butisnotasuperglobal.(Notethat $HTTP_SESSION_VARSand$_SESSIONaredifferentvariablesandthatPHPhandlesthemassuch)
ChangeLog
Version 4.1.0 Description Introduced$_SESSIONthatthedeprecated$HTTP_SESSION_VARS.
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods.
SeeAlso
session_start()
$_ENV $HTTP_ENV_VARS[deprecated]
$_ENV$HTTP_ENV_VARS[deprecated]Environmentvariables
Description
Anassociativearrayofvariablespassedtothecurrentscriptviatheenvironmentmethod. ThesevariablesareimportedintoPHP'sglobalnamespacefromtheenvironmentunderwhichthePHPparser isrunning.ManyareprovidedbytheshellunderwhichPHPisrunninganddifferentsystemsarelikely runningdifferentkindsofshells,adefinitivelistisimpossible.Pleaseseeyourshell'sdocumentationfora listofdefinedenvironmentvariables.
ChangeLog
Version 4.1.0 Description Introduced$_ENVthatdeprecated$HTTP_ENV_VARS.
Examples
Example#1$_ENVexample <?php echo'Myusernameis'.$_ENV["USER"].'!'; ?> Assuming"bjori"executesthisscript Theaboveexamplewilloutputsomethingsimilarto:
Myusernameisbjori!
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods.
SeeAlso
getenv() Thefilterextension
$_COOKIE $HTTP_COOKIE_VARS[deprecated]
$_COOKIE$HTTP_COOKIE_VARS[deprecated]HTTPCookies
Description
AnassociativearrayofvariablespassedtothecurrentscriptviaHTTPCookies. $HTTP_COOKIE_VARScontainsthesameinitialinformation,butisnotasuperglobal.(Notethat $HTTP_COOKIE_VARSand$_COOKIEaredifferentvariablesandthatPHPhandlesthemassuch)
ChangeLog
Version 4.1.0 Description Introduced$_COOKIEthatdeprecated$HTTP_COOKIE_VARS.
Examples
Example#1$_COOKIEexample <?php echo'Hello'.htmlspecialchars($_COOKIE["name"]).'!'; ?> Assumingthe"name"cookiehasbeensetearlier Theaboveexamplewilloutputsomethingsimilarto:
HelloHannes!
Notes
Note:Thisisa'superglobal',orautomaticglobal,variable.Thissimplymeansthatitisavailable inallscopesthroughoutascript.Thereisnoneedtodoglobal$variable;toaccessitwithin functionsormethods.
SeeAlso
setcookie()
Handlingexternalvariables Thefilterextension
$php_errormsg
$php_errormsgThepreviouserrormessage
Description
$php_errormsgisavariablecontainingthetextofthelasterrormessagegeneratedbyPHP.Thisvariable willonlybeavailablewithinthescopeinwhichtheerroroccurred,andonlyifthetrack_errorsconfiguration optionisturnedon(itdefaultstooff). Note:Thisvariableisonlyavailablewhentrack_errorsisenabledinphp.ini. Warning Ifauserdefinederrorhandlerisset$php_erromsgisonlysetiftheerrorhandlerreturnsFALSE
Examples
Example#1$php_errormsgexample <?php @strpos(); echo$php_errormsg; ?> Theaboveexamplewilloutputsomethingsimilarto:
Wrongparametercountforstrpos()
$HTTP_RAW_POST_DATA
$HTTP_RAW_POST_DATARawPOSTdata
Description
$HTTP_RAW_POST_DATAcontainstherawPOSTdata.Seealways_populate_raw_post_data
$http_response_header
$http_response_headerHTTPresponseheaders
Description
The$http_response_headerarrayissimilartotheget_headers()function.WhenusingtheHTTPwrapper, $http_response_headerwillbepopulatedwiththeHTTPresponseheaders.
Examples
Example#1$http_response_headerexample <?php file_get_contents("http://example.com"); var_dump($http_response_header); ?> Theaboveexamplewilloutputsomethingsimilarto:
array(9){ [0]=> string(15)"HTTP/1.1200OK" [1]=> string(35)"Date:Sat,12Apr200817:30:38GMT" [2]=> string(29)"Server:Apache/2.2.3(CentOS)" [3]=> string(44)"LastModified:Tue,15Nov200513:24:10GMT" [4]=> string(27)"ETag:"2801001b680bfd280"" [5]=> string(20)"AcceptRanges:bytes" [6]=> string(19)"ContentLength:438" [7]=> string(17)"Connection:close" [8]=> string(38)"ContentType:text/html;charset=UTF8" }
$argc
$argcThenumberofargumentspassedtoscript
Description
Containsthenumberofargumentspassedtothecurrentscriptwhenrunningfromthecommandline. Note:Thescript'sfilenameisalwayspassedasanargumenttothescript,thereforetheminimum valueof$argcis1. Note:Thisvariableisonlyavailablewhenregister_argc_argvisenabled.
Examples
Example#1$argcexample <?php var_dump($argc); ?> Whenexecutingtheexamplewith:phpscript.phparg1arg2arg3 Theaboveexamplewilloutputsomethingsimilarto:
int(4)
$argv
$argvArrayofargumentspassedtoscript
Description
Containsanarrayofalltheargumentspassedtothescriptwhenrunningfromthecommandline. Note:Thefirstargumentisalwaysthecurrentscript'sfilename,therefore$argv[0]isthescript's name. Note:Thisvariableisonlyavailablewhenregister_argc_argvisenabled.
Examples
Example#1$argvexample <?php var_dump($argv); ?> Whenexecutingtheexamplewith:phpscript.phparg1arg2arg3 Theaboveexamplewilloutputsomethingsimilarto:
array(4){ [0]=> string(10)"script.php" [1]=> string(4)"arg1" [2]=> string(4)"arg2" [3]=> string(4)"arg3" }
TableofContents
Superglobals Superglobalsarebuiltinvariablesthatarealwaysavailableinallscopes $GLOBALS Referencesallvariablesavailableinglobalscope $_SERVER Serverandexecutionenvironmentinformation $_GET HTTPGETvariables $_POST HTTPPOSTvariables $_FILES HTTPFileUploadvariables $_REQUEST HTTPRequestvariables $_SESSION Sessionvariables $_ENV Environmentvariables $_COOKIE HTTPCookies $php_errormsg Thepreviouserrormessage $HTTP_RAW_POST_DATA RawPOSTdata $http_response_header HTTPresponseheaders $argc Thenumberofargumentspassedtoscript $argv Arrayofargumentspassedtoscript
PredefinedExceptions
TableofContents
Exception ErrorException
Exception
Introduction
ExceptionisthebaseclassforallExceptions.
Classsynopsis
Exception Exception{ /*Properties*/ protectedstring$message; privatestring$string; protectedint$code; protectedstring$file; protectedint$line; privatearray$trace; /*Methods*/ publicException::__construct([string$message=NULL[,int$code=0]]) finalpublicstringException::getMessage(void) finalpublicintException::getCode(void) finalpublicstringException::getFile(void) finalpublicstringException::getLine(void) finalpublicarrayException::getTrace(void) finalpublicstringException::getTraceAsString(void) publicstringException::__toString(void) finalprivatestringException::__clone(void) }
Properties
message
Theexceptionmessage string InternalExceptionname code TheExceptioncode file Thefilenamewheretheexceptionwasthrown line Thelinewheretheexceptionwasthrown trace Thestacktrace
Exception::__construct
(Noversioninformationavailable,mightbeonlyinCVS) Exception::__constructConstructtheexception
Description
publicException::__construct([string$message=NULL[,int$code=0]]) ConstructstheException.
Parameters
message TheExceptionmessagetothrow. code TheExceptioncode.
Exception::getMessage
(PHP5>=5.1.0) Exception::getMessageGetstheExceptionmessage
Description
finalpublicstringException::getMessage(void) ReturnstheExceptionmessage.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
ReturnstheExceptionmessageasastring.
Examples
Example#1Exception::getMessage()example <?php try{ thrownewException("Someerrormessage"); }catch(Exception$e){ echo$e>getMessage(); } ?> Theaboveexamplewilloutputsomethingsimilarto:
Someerrormessage
Exception::getCode
(PHP5>=5.1.0) Exception::getCodeGetstheExceptioncode
Description
finalpublicintException::getCode(void) ReturnstheExceptioncode.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
ReturnstheExceptioncodeasainteger.
Examples
Example#1Exception::getCode()example <?php try{ thrownewException("Someerrormessage",30); }catch(Exception$e){ echo"Theexceptioncodeis:".$e>getCode(); } ?> Theaboveexamplewilloutputsomethingsimilarto:
Theexceptioncodeis:30
Exception::getFile
(PHP5>=5.1.0) Exception::getFileGetsthefileinwhichtheexceptionoccurred
Description
finalpublicstringException::getFile(void) Getthenameofthefiletheexceptionwasthrownfrom.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
Returnsthefilenameinwhichtheexceptionwasthrown.
Examples
Example#1Exception::getFile()example <?php try{ thrownewException; }catch(Exception$e){ echo$e>getFile(); } ?> Theaboveexamplewilloutputsomethingsimilarto:
/home/bjori/tmp/ex.php
Exception::getLine
(PHP5>=5.1.0) Exception::getLineGetsthelineinwhichtheexceptionoccurred
Description
finalpublicstringException::getLine(void) Returnslinenumberwheretheexceptionwasthrown.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
Returnsthelinenumberwheretheexceptionwasthrown.
Examples
Example#1Exception::getLine()example <?php try{ thrownewException("Someerrormessage"); }catch(Exception$e){ echo"Theexceptionwasthrownonline:".$e>getLine(); } ?> Theaboveexamplewilloutputsomethingsimilarto:
Theexceptionwasthrownonline:3
Exception::getTrace
(PHP5>=5.1.0) Exception::getTraceGetsthestacktrace
Description
finalpublicarrayException::getTrace(void) ReturnstheExceptionstacktrace.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
ReturnstheExceptionstacktraceasanarray.
Examples
Example#1Exception::getTrace()example <?php functiontest(){ thrownewException; } try{ test(); }catch(Exception$e){ var_dump($e>getTrace()); } ?> Theaboveexamplewilloutputsomethingsimilarto:
array(1){ [0]=> array(4){ ["file"]=> string(22)"/home/bjori/tmp/ex.php" ["line"]=> int(7) ["function"]=> string(4)"test" ["args"]=> array(0){ } } }
Exception::getTraceAsString
(PHP5>=5.1.0) Exception::getTraceAsStringGetsthestacktraceasastring
Description
finalpublicstringException::getTraceAsString(void)
ReturnstheExceptionstacktraceasastring.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
ReturnstheExceptionstacktraceasastring.
Examples
Example#1Exception::getTraceAsString()example <?php functiontest(){ thrownewException; } try{ test(); }catch(Exception$e){ echo$e>getTraceAsString(); } ?> Theaboveexamplewilloutputsomethingsimilarto:
#0/home/bjori/tmp/ex.php(7):test() #1{main}
Exception::__toString
(PHP5>=5.1.0) Exception::__toStringStringrepresentationoftheexception
Description
publicstringException::__toString(void) Returnsthestringrepresentationoftheexception.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
Returnsthestringrepresentationoftheexception.
Examples
Example#1Exception::__toString()example <?php try{ thrownewException("Someerrormessage"); }catch(Exception$e){ echo$e; } ?> Theaboveexamplewilloutputsomethingsimilarto:
exception'Exception'withmessage'Someerrormessage'in/home/bjori/tmp/ex.php:3 Stacktrace: #0{main}
Exception::__clone
(PHP5>=5.1.0) Exception::__cloneClonetheexception
Description
finalprivatestringException::__clone(void) TriestoclonetheException,whichresultsinFatalerror.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
Novalueisreturned.
Errors/Exceptions
Exceptionsarenotclonable.
TableofContents
Exception::__construct Constructtheexception Exception::getMessage GetstheExceptionmessage Exception::getCode GetstheExceptioncode Exception::getFile Getsthefileinwhichtheexceptionoccurred Exception::getLine Getsthelineinwhichtheexceptionoccurred Exception::getTrace Getsthestacktrace Exception::getTraceAsString Getsthestacktraceasastring Exception::__toString Stringrepresentationoftheexception Exception::__clone Clonetheexception
ErrorException
Introduction
AnErrorException.
Classsynopsis
ErrorException ErrorExceptionextendsException{ /*Properties*/ protectedint$severity; /*Methods*/ publicErrorException::__construct([string$message[,int$code[,int$severity[,string $filename[,int$lineno]]]]]) finalpublicintErrorException::getSeverity(void) /*Inheritedmethods*/ finalpublicstringException::getMessage(void)
Properties
severity Theseverityoftheexception
Examples
Example#1TurnallerrormessagesintoErrorException. <?php functionexception_error_handler($errno,$errstr,$errfile,$errline){ thrownewErrorException($errstr,0,$errno,$errfile,$errline); } set_error_handler("exception_error_handler"); /*Triggerexception*/ strpos(); ?> Theaboveexamplewilloutputsomethingsimilarto:
Fatalerror:Uncaughtexception'ErrorException'withmessage'Wrongparametercount forstrpos()'in/home/bjori/tmp/ex.php:8 Stacktrace: #0[internalfunction]:exception_error_handler(2,'Wrongparameter...', '/home/bjori/php...',8,Array) #1/home/bjori/php/cleandocs/test.php(8):strpos() #2{main} thrownin/home/bjori/tmp/ex.phponline8
ErrorException::__construct
(Noversioninformationavailable,mightbeonlyinCVS) ErrorException::__constructConstructtheexception
Description
publicErrorException::__construct([string$message[,int$code[,int$severity[,string $filename[,int$lineno]]]]]) ConstructstheException.
Parameters
message TheExceptionmessagetothrow. code TheExceptioncode. severity Theseverityleveloftheexception. filename Thefilenamewheretheexceptionisthrown. lineno Thelinenumberwheretheexceptionisthrown.
ErrorException::getSeverity
(PHP5>=5.1.0) ErrorException::getSeverityGetstheexceptionseverity
Description
finalpublicintErrorException::getSeverity(void) Returnstheseverityoftheexception.
Parameters
Thisfunctionhasnoparameters.
ReturnValues
Returnstheseverityleveloftheexception.
Examples
Example#1ErrorException()example <?php try{ thrownewErrorException("Exceptionmessage",0,75); }catch(ErrorException$e){ echo"Thisexceptionseverityis:".$e>getSeverity(); } ?> Theaboveexamplewilloutputsomethingsimilarto:
Thisexceptionseverityis:75
TableofContents
Contextoptionsandparameters
PHPoffersvariouscontextoptionsandparameterswhichcanbeusedwithallfilesystemandstream wrappers.Thecontextiscreatedwithstream_context_create().Optionsaresetwith stream_context_set_option()andparameterswithstream_context_set_params().
Socketcontextoptions
SocketcontextoptionsSocketcontextoptionlisting
Description
Socketcontextoptionsareavailableforallwrappersthatworkoversockets,liketcp,httpandftp.
Options
bindto UsedtospecifytheIPaddress(eitherIPv4orIPv6)and/ortheportnumberthatPHPwillusetoaccess thenetwork.Thesyntaxisip:port.SettingtheIPortheportto0willletthesystemchoosetheIP and/orport. Note:AsFTPcreatestwosocketconnectionsduringnormaloperation,theportnumber cannotbespecifiedusingthisoption.
ChangeLog
Version 5.1.0 Description Addedbindto.
Examples
Example#1Basicbindtousageexample <?php //connecttotheinternetusingthe'192.168.0.100'IP $opts=array( 'socket'=>array( 'bindto'=>'192.168.0.100:0', ), ); //connecttotheinternetusingthe'192.168.0.100'IPandport'7000' $opts=array( 'socket'=>array( 'bindto'=>'192.168.0.100:7000', ), );
HTTPcontextoptions
HTTPcontextoptionsHTTPcontextoptionlisting
Description
Contextoptionsforhttp://andhttps://transports.
Options
methodstring GET,POST,oranyotherHTTPmethodsupportedbytheremoteserver. DefaultstoGET. headerstring Additionalheaderstobesentduringrequest.Valuesinthisoptionwilloverrideothervalues(suchas Useragent:,Host:,andAuthentication:). user_agentstring ValuetosendwithUserAgent:header.Thisvaluewillonlybeusedifuseragentisnotspecifiedinthe headercontextoptionabove. Bydefaulttheuser_agentphp.inisettingisused. contentstring
Additionaldatatobesentaftertheheaders.TypicallyusedwithPOSTorPUTrequests. proxystring URIspecifyingaddressofproxyserver.(e.g.tcp://proxy.example.com:5100). request_fulluriboolean WhensettoTRUE,theentireURIwillbeusedwhenconstructingtherequest.(i.e.GET http://www.example.com/path/to/file.htmlHTTP/1.0).Whilethisisanonstandardrequestformat, someproxyserversrequireit. DefaultstoFALSE. max_redirectsinteger Themaxnumberofredirectstofollow.Value1orlessmeansthatnoredirectsarefollowed. Defaultsto20. protocol_versionfloat HTTPprotocolversion. Defaultsto1.0. timeoutfloat Readtimeoutinseconds,specifiedbyafloat(e.g.10.5). Bydefaultthedefault_socket_timeoutphp.inisettingisused. ignore_errorsboolean Fetchthecontentevenonfailurestatuscodes. DefaultstoFALSE
ChangeLog
Version 5.3.0 5.2.1 5.1.0 Description Addedignore_errors. Addedtimeout. AddedHTTPSproxyingthroughHTTPproxies. 5.1.0 Addedmax_redirects.
Version 5.1.0
Description Addedprotocol_version.
Examples
Example#1FetchapageandsendPOSTdata <?php $postdata=http_build_query( array( 'var1'=>'somecontent', 'var2'=>'doh' ) ); $opts=array('http'=> array( 'method'=>'POST', 'header'=>'Contenttype:application/xwwwformurlencoded', 'content'=>$postdata ) ); $context=stream_context_create($opts); $result=file_get_contents('http://example.com/submit.php',false,$cont ext); ?>
Notes
Note:Underlyingsocketstreamcontextoptions AdditionalcontextoptionsmaybesupportedbytheunderlyingtransportForhttp://streams,refer tocontextoptionsforthetcp://transport.Forhttps://streams,refertocontextoptionsforthe ssl://transport.
SeeAlso
Socketcontextoptions SSLcontextoptions
FTPcontextoptions
FTPcontextoptionsFTPcontextoptionlisting
Description
Contextoptionsforftp://andftps://transports.
Options
overwriteboolean Allowoverwritingofalreadyexistingfilesonremoteserver.Appliestowritemode(uploading)only. DefaultstoFALSE. resume_posinteger Fileoffsetatwhichtobegintransfer.Appliestoreadmode(downloading)only. Defaultsto0(BeginningofFile). proxystring ProxyFTPrequestviahttpproxyserver.Appliestofilereadoperationsonly.Ex: tcp://squid.example.com:8000.
ChangeLog
Version 5.1.0 5.0.0 Description Addedproxy. Addedoverwriteandresume_pos.
Notes
Note:Underlyingsocketstreamcontextoptions AdditionalcontextoptionsmaybesupportedbytheunderlyingtransportForftp://streams,refer tocontextoptionsforthetcp://transport.Forftps://streams,refertocontextoptionsforthessl:// transport.
SeeAlso
Socketcontextoptions SSLcontextoptions
SSLcontextoptions
SSLcontextoptionsSSLcontextoptionlisting
Description
Contextoptionsforssl://andtls://transports.
Options
verify_peerboolean RequireverificationofSSLcertificateused. DefaultstoFALSE. allow_self_signedboolean Allowselfsignedcertificates. DefaultstoFALSE cafilestring LocationofCertificateAuthorityfileonlocalfilesystemwhichshouldbeusedwiththeverify_peer contextoptiontoauthenticatetheidentityoftheremotepeer. capathstring Ifcafileisnotspecifiedorifthecertificateisnotfoundthere,thedirectorypointedtobycapathis searchedforasuitablecertificate.capathmustbeacorrectlyhashedcertificatedirectory. local_certstring Pathtolocalcertificatefileonfilesystem.ItmustbeaPEMencodedfilewhichcontainsyour certificateandprivatekey.Itcanoptionallycontainthecertificatechainofissuers. passphrasestring
Passphrasewithwhichyourlocal_certfilewasencoded. CN_matchstring CommonNameweareexpecting.PHPwillperformlimitedwildcardmatching.IftheCommonName doesnotmatchthis,theconnectionattemptwillfail. verify_depthinteger Abortifthecertificatechainistoodeep. Defaultstonoverification. ciphersstring Setsthelistofavailableciphers.Theformatofthestringisdescribedinciphers(1). DefaultstoDEFAULT. capture_peer_certboolean IfsettoTRUEapeer_certificatecontextoptionwillbecreatedcontainingthepeercertificate. capture_peer_chainboolean IfsettoTRUEapeer_certificate_chaincontextoptionwillbecreatedcontainingthecertificatechain.
ChangeLog
Version 5.0.0 Description Addedcapture_peer_cert,capture_peer_chainandciphers.
Notes
Note:Becausessl://istheunderlyingtransportforthehttps://andftps://wrappers,anycontext optionswhichapplytossl://alsoapplytohttps://andftps://.
SeeAlso
Socketcontextoptions
CURLcontextoptions
CURLcontextoptionsCURLcontextoptionlisting
Description
CURLcontextoptionsareavailablewhentheCURLextensionwascompiledusingthewithcurlwrappers configureoption.
Options
methodstring GET,POST,oranyotherHTTPmethodsupportedbytheremoteserver. DefaultstoGET. headerstring Additionalheaderstobesentduringrequest.Valuesinthisoptionwilloverrideothervalues(suchas Useragent:,Host:,andAuthentication:). user_agentstring ValuetosendwithUserAgent:header. Bydefaulttheuser_agentphp.inisettingisused. contentstring Additionaldatatobesentaftertheheaders.ThisoptionisnotusedforGETorHEADrequests. proxystring URIspecifyingaddressofproxyserver.(e.g.tcp://proxy.example.com:5100). max_redirectsinteger Themaxnumberofredirectstofollow.Value1orlessmeansthatnoredirectsarefollowed. Defaultsto20. curl_verify_ssl_hostboolean