Tải bản đầy đủ - 0 (trang)
Chapter 2. The PHP Scripting Language

Chapter 2. The PHP Scripting Language

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

2.1IntroducingPHP

ThecurrentversionofPHPisPHP4(Version4.3.4).PHP5is

availableforbetatestingatthetimeofwritingasVersion

5.0.0b3.Wediscussbothversionsinthischapter.

PHPisarecursiveacronymthatstandsforPHP:Hypertext

Preprocessor;thisisinthenamingstyleofGNU,whichstands

forGNU'sNotUnixandwhichbeganthisoddtrend.Thename

isn'taparticularlygooddescriptionofwhatPHPisandwhatit's

commonlyusedfor.PHPisascriptinglanguagethat'susually

embeddedorcombinedwiththeHTMLofawebpage.Whenthe

pageisrequested,thewebserverexecutesthePHPscriptand

substitutesintheresultbackintothepage.PHPhasmany

excellentlibrariesthatprovidefast,customizedaccessto

DBMSsandisanidealtoolfordevelopingapplicationlogicin

themiddletierofathree-tierapplication.



2.1.1PHPBasics

Example2-1showsthefirstPHPscriptinthisbook,the

ubiquitous"Hello,world."It'sactuallymostlyHTML;thePHPis

embeddedneartheend.



Example2-1.TheubiquitousHello,worldinPHP




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








Hello,world








print"Hello,world";

?>









Whenrequestedbyawebbrowser,thescriptisrunontheweb

serverandtheresultingHTMLdocumentsentbacktothe

browserandrenderedasshowninFigure2-1.



Figure2-1.TheoutputofExample2-1shownin

theNetscapebrowser



Example2-1illustratesthebasicfeaturesofaPHPscript.It'sa

mixtureofHTMLinthiscaseit'smostlyHTMLandPHPcode.The

PHPcodeinthisexample:


print"Hello,world";

?>



simplyprintsthegreeting,"Hello,world."

ThePHPscriptshowninExample2-1isratherpointless:we

couldsimplyhaveauthoredtheHTMLtoincludethegreeting

directly.BecausePHPintegratessowellwithHTML,usingPHP

toproducestaticsequenceofcharactersisfarlesscomplicated

andlessinterestingthanusingotherhigh-levellanguages.

However,theexampledoesillustrateseveralfeaturesofPHP:

AblockofPHPcodeisembeddedwithinHTMLusingthe

beginandendtags.Otherbeginandendtag

stylescanalsobeused,suchastheHTMLstylethatisused

withJavaScriptorotherembeddedscripts:
language="PHP">and.There'salsoashorter



style.Forconsistency,weuseonlythe
?>styleinthisbook.

Whitespacehasnoeffect,excepttoaidreadabilityforthe

developer.Forexample,thePHPcouldhavebeenwritten

succinctlyaswiththe

sameeffect.Anymixofwhitespacecharactersspaces,tabs,

carriagereturns,andsooncanbeusedtoseparatePHP

statements.

APHPscriptisaseriesofstatements,eachterminatedwith

asemicolon.Oursimpleexamplehasonlyonestatement:

print"Hello,world";.PHPscriptcanbeanywhereina

fileandinterleavedwithanyHTMLfragment.WhileExample

2-1containsonlyonestatementwithinonesetof
and?>tags,statementscanbedistributecodeacross

multipleblocksofcode.

WhenPHPscriptisrun,eachblockofcode,includingthe

startandendscripttagsisreplacedwiththe

outputoftheblock.



Whenwepresentafewlinesofcodethataresectionsoflargerscripts,

weusuallyomitthestartandendtags.



ThepointoflearningPHP,ofcourse,istocreatepagesthat

change,pagesthatcontaindynamiccontentderivedfromuser

inputoradatabase.Thefirststeptowardthatgoalisto

introduceavariable,whichissomethingthatcanchangefrom

runtorun.Inthischapter,wedon'tusedynamiccontent.But

wecanshowhowtosetavariabletoastringasfollows:





Andthenrewriteourscriptasfollows:





Because$outputStringhasbeensettoHello,world,that

stringisprintedaspartofthesurroundingHTMLpage.

ThefreedomtointerleaveblocksofPHPstatementswithHTML

isoneofthemostpowerfulfeaturesofPHP.Ashortexampleis

showninExample2-2;thevariable$outputStringisinitialized

beforethestartoftheHTMLdocument,andlaterthisvariableis

outputtwice,aspartoftheand<body>elements.We<br /><br />discussmoreaboutvariablesandhowtousethemlaterinthis<br /><br />chapter.<br /><br /><br /><br />Example2-2.Embeddingthreeblocksofcodeina<br /><br />singledocument<br /><br /><?php$outputString="Hello,world";?><br /><br /><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"<br /><br /><br /><br />"http://www.w3.org/TR/html401/loose.dtd"><br /><br /><html><br /><br /><head><br /><br /><br /><br /><metahttp-equiv="Content-Type"content="text/html;charset=i<br /><br /><title><?phpprint$outputString;?>















TheflexibilitytoaddmultipleblocksofPHPtoHTMLcanalso

leadtounwieldy,hard-to-maintaincode.Careshouldbetaken

inmodularizingcodeandHTML;wediscusshowtoseparate

codeandHTMLusingtemplatesinChapter7.



2.1.1.1CreatingPHPscripts

APHPscriptcanbewrittenusingplaintextandcanbecreated

withanytexteditor,suchastheUnixeditorsjoe,vi,nedit,

Emacs,orpico,oraMicrosoftWindowseditorsuchasNotepad

orWordPad.Therearealsoseveralspecial-purposePHP

programmingeditorsavailable,andawell-maintainedlistof

thesecanbefoundathttp://phpeditors.linuxbackup.co.uk/.

IfyousaveaPHPscriptinafilewitha.phpextensionunderthe

directoryconfiguredasApache'sdocumentroot,Apache

executesthescriptwhenarequestismadefortheresource.

FollowingtheinstallationinstructionsgiveninAppendixA

throughAppendixC,thedocumentrootonaUnixmachineis:

/usr/local/apache/htdocs/



andinaMicrosoftWindowsenvironment:

C:\ProgramFiles\EasyPHP1-7\www\



ConsiderwhathappenswhenthescriptshowninExample2-1

issavedinthefileexample.2-1.phpinthedocumentroot

directoryandyouviewthefileinaWebbrowseronthesame

machine.ApachewhenconfiguredwiththePHPmoduleexecutes

thescriptwhenrequeststotheURLhttp://localhost/example.21.phparemade.

IfyouareworkingonaUnixhost,anddirectorypermissions

don'tpermitcreationoffilesinthedocumentroot,it'salso

possibletoworkinyouruserhomedirectory.Iftheinstallation

instructionsinAppendixAthroughAppendixChavebeen

followed,adirectorycanbecreatedbeneathyourUnixhome

directoryandthepermissionssetsothatthedirectoryis

readablebythewebserver.Youcandothisbyrunninga

terminalwindowandtypingthefollowingaftertheshellprompt

(shownhereasa%):

%mkdir~/public_html

%chmoda+rx~/public_html



Theexamplefilecanthenbecreatedwiththefilename:

~/public_html/example.2-1.php



ThefilecanthenberetrievedwiththeURL

http://localhost/~user/example.2-1.php,whereuseristhe



userloginname.

Youcaninsertanyofthecodeinthischapterintothatfile,or

anotheroneofyourchoice,andseewhat'sdisplayedbycalling

itupinabrowseraswehaveshown.



2.1.1.2Comments

Commentscanbeincludedincodeusingseveralstylesusedby

high-levelprogramminglanguages.Thisincludesthefollowing

styles:

//Thisisaone-linecomment



#Thisisanotherone-linecommentstyle



/*Thisishowyou

cancreateamulti-line

comment*/



2.1.1.3Outputtingdatawithechoandprint

TheprintstatementusedinExample2-1andExample2-2is

frequentlyusedandcanoutputanytypeofdata.Theecho

statementcanbeusedforthesamepurpose.Considersome

examples:



print"Hello,world";



//echoworksjustthesame

echo"Hello,world";



//numberscanbeprintedwithechotoo

echo123;



//Socanthecontentsofvariables

$outputString="Hi!";

echo$outputString;



Thedifferencebetweenprintandechoisthatechocanoutput

morethanoneparameter,eachseparatedbyacomma.For

example,echocanprintastringandanintegertogetherinthe

onemessage:

//prints"Theansweris42"

echo"Theansweris",42;



Theprintandechostatementsarealsooftenseenwith

parentheses:



echo"hello";



//isthesameas

echo("hello");



Parenthesesmakenodifferencetothebehaviorofprint.

However,whentheyareusedwithecho,onlyoneoutput

parametercanbeprovided.

Theechoandprintstatementscanbeusedformosttasksand

canoutputanycombinationofstaticstrings,numbers,arrays,

andothervariabletypesdiscussedlaterinthischapter.We

discussmorecomplexoutputwithprintf()inthenextchapter.



2.1.2StringLiterals

OneofthemostcommontasksinaPHPscriptistooutput

literalsequencesofcharacterstocreatemessages,headings,

andothertextthatappearonHTMLpages.Aliteralsequenceof

charactersastringliteralorsimplyastringcanbeincludedina

PHPscriptusingquotationcharacters.PHPcancreatedoubleandsingle-quotedstringliterals:

print'Thisworks';

print"justlikethis.";



Becausequotationmarksareusedtomarkthestartandendof

strings,aquotationmarkthatisactuallypartofastringmust



bemarkedinsomeway.Markingacharactersothatitis

treatedasanormalcharacter,insteadofbeingpartofthePHP

syntax,iscalledescaping.Quotationmarkscanbeescapedby

puttingabackslashbeforethem:

print"Thisstringhasa\":adoublequote!";

print'Thisstringhasa\':asinglequote!';



Asimplealternativetoincludingquotationmarksinastringis

toswitchtothesingle-quotationstyle:

//Andherearesomestringsthatcontainquotes

print"Thisstringhasa':asinglequote!";

print'Thisstringhasa":adoublequote!';



Toincludeabackslashcharacterinadouble-quotedstring,use

theescapedsequence\\.Tab,newline(linebreak),and

carriage-returncharacterscanbeincludedinadouble-quoted

stringusingtheescapesequences\t,\n,and\r,respectively.

Insertingthewhitespacecharacters\t,\n,and\risoften

usefultomakeoutputmorereadable,howeverasHTML,white

spaceisgenerallydisregarded.

Unlikemanyotherlanguages,PHPallowsnewlinecharactersto

beincludeddirectlyinastringliteral.Thefollowingexample

showsthevariable$varassignedwithastringthatcontainsa

newlinecharacter:

//ThisisOk.$varcontainsanewlinecharacter



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

Chapter 2. The PHP Scripting Language

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

×