Você está na página 1de 10

PHP Primer

Introduction
PH P is a ge ne ral -purpos e s cripting l
anguage e s pe cial l
y s uite d
for W e b de ve lopm e nt. Itis ope n-s ource and can be de pl oye d
on al lm ajor ope rating s ys te m s and w e b s e rve rs fre e ofch arge .
Itis im pe rative , re fl
e ctive and s upports obje ct-orie nte d
program m ing.

Bas ic Syntax
Sim il
aritie s w ith oth e r im pe rative l
anguage s

PH P code s h oul dlook fam il iar to anyone w h o h as h ad


e xpe rie nce w ith C, C+ + or Java. State m e nts are te rm inate d
w ith a ";" and bl ock s ofcode are de l im ite d w ith "{" and "}". Th e
"/*...*/" and "//" notations are both val id for PH P. Control
s tructure s s uch as if-e l
s e s tate m e nts , for l
oops and w h il e l oops
w ork in m uch th e s am e w ay as w ith th e above m e ntione d
language s .

H ow e ve r, th e re are s om e diffe re nce s and fe ature s th atare


uniq ue to PH P w h ich w il lbe brie fl y e xpl
ore d in th e re s tofth is
prim e r.

Variabl
es

Variabl e s in PH P are re pre s e nte d by a "$" ch aracte r fol low e d


by th e nam e ofth e variabl e . For e xam ple , th e variabl e "foobar"
w oul d be re pre s e nte d as "$foobar" in PH P code . Variabl e
nam e s in PH P are cas e -s e ns itive and m us ts tartw ith e ith e r an
unde rs core or a l e tte r, fol
low e d by any num be r ofl e tte rs ,
num be rs or unde rs core s . Th e fol low ing code s tub
de m ons trate s th e as s ignm e ntofa val ue to a variabl e.

$foo = 'bar';
Note th atPH P doe s notby de faul te nforce th e de claration ofa
variabl e be fore its us age , s o s om e care s h oul d be tak e n notto
atte m ptto acce s s th e value ofa variabl e be fore one h as be e n
as s igne d to it.

Es caping H TM L

PH P code can e m be dde d w ith in H TM Lus ing th e "<?ph p" and


"?>" tags . For e xam pl
e , th e fol
low ing code w ould output"H e l
lo,
foobar!".

<html>
<body>
<?php $lastname = "bar"; ?>
Hello, foo<?php echo $lastname; ?>!
</body>
</html>

Type s
PH P s upports th e fol
low ing e igh tprim itive data type s .

four s cal ar type s : bool e an, inte ge r, fl


oat, s tring
tw o com pound type s : array, obje ct
tw o s pe cialtype s : re s ource , NULL

PH P is a w e ak l y-type d l anguage . Th is m e ans th atth e


program m e r is us ual ly notre q uire d to re s ol
ve th e type ofa
variabl e . Ins te ad, th e type ofa variabl e is us ual ly re s ol
ve d
during runtim e de pe nding on th e conte xtin w h ich itis be ing
us e d. Th is can s om e tim e s be trick y, as w e s h al ls e e .

Bool
e ans

Th e bool
e an type can tak e th e val
ue s true or fal
s e . Since PH P
is w e ak ly-type d, variabl e s ofoth e r type s can be im plicitl
y cas t
as bool e ans . H ow e ve r, one m us tbe care fulw h e n doing th is ,
be caus e s om e val ue s ofoth e r type s are e val uate d to FALSE,
as lis te d be l
ow .

- th e inte ge r 0 and th e float0.0


- th e s tring "0" and e m pty s trings
- an array w ith z e ro e le m e nts
- an obje ctw ith z e ro m e m be r variabl
e s (PH P 4 onl
y)
- th e NULLs pe cialtype

Inte ge rs and fl
oats

Inte ge rs can be s pe cifie d in de cim al(10-bas e d), h e xade cim al


(16-bas e d) or octal(8-bas e d) notation, optional l
y pre ce de d by
a s ign (- or + ). O ctalnum be rs are pre ce de d by 0 and
h e xade cim al s are pre ce de d by 0x.

Fl oating pointnum be rs can be s pe cifie d in any ofth e fol


low ing
th re e form ats .

$a = 1.234;
$b = 1.2e3;
$c = 7E-10;

Strings

A s tring in PH P can be s pe cifie d w ith s ingl e q uote s , double


q uote s or th e h e re doc s yntax. Since th is is a jus ta prim e r, th e
h e re doc s yntax w il lnotbe cove re d for th e s ak e ofbre vity.

Th e s im pl e s tw ay to s pe cify a s tring is to de lim ititw ith s ingl e


q uote s . To s pe cify a s ingle q uote w ith in a s ingl e -q uote d s tring,
itne e ds to be pre ce de d by a back s l as h (\). Ifa back s l as h is to
occur be fore a s ingl e q uote , th e n a doubl e back s l as h is
re q uire d. O th e rw is e , th e re is norm al ly no ne e d to e s cape
back s l as h e s . For e xam pl e , th e code be l
ow w oul d print"Th is is
a back s l as h \, a s ingl e q uote ' and a back s l as h follow e d by a
s ingle q uote \'".

echo 'This is a backslash \, a single quote


\' and a backslash followed by a single quote
\\'';

For doubl e -q uote d s trings in PH P, m ore ofth e e s cape


s e q ue nce s found in oth e r l anguage s m ay be us e d, s uch as
"\n", "\t" and "\r". H ow e ve r, th e m os tim portantfe ature ofdoubl e-
q uote d s trings in PH P is th atvariabl e s are e xpande d. For
e xam pl e , th e code be l ow w ould print"Variabl e $foo h as a val
ue
ofbar".

$foo = 'ba'.'r'; //'.' is the concatenation


operator
echo "Variable \$foo has a value of $foo";

Arrays

Itis be yond th e s cope ofth is prim e r to ful


ly de s cribe th e PH P
array type , s o onl y a brie fs um m ary w il
lbe give n. An array in
PH P is an orde re d m ap. A m ap is a type th atm aps val ue s to
k e ys . An array in PH P m ay be cre ate d us ing th e array()
function, as s h ow n be low .

$arr=array("key1"=>"val1","key2"=>"val2","val
3");

Th e above s tate m e ntw oul d re s ultin an array w ith th e e l


e m e nts
val 1, val 2 and val 3. Since th e k e y ofval 3 w as nots pe cifie d, it
w oul d tak e th e val ue 0, th e s m al l
e s tavail
abl e non-ne gative
inte ge r. Alte rnative l
y, th e above array coul d h ave be e n
s pe cifie d us ing th e fol
low ing s yntax.

$arr['key1'] = 'val1'; //$arr is created


$arr['key2'] = 'val2';
$arr[] = 'val3'; //$arr[0] is equivalent

Le galval ue s for k e ys ofarrays are any val ue s ofprim itive


type s , w ith bool e an true and fals e be ing cas tas 1 and 0
re s pe ctive ly. Fl
oating pointnum be rs us e d as k e ys are
truncate d and NULLis cas tas an e m pty s tring. An e m pty
s tring, ofcours e , re m ains an e m pty s tring.

O bje cts

O bje cts in PH P, lik e arrays , is a ve ry w ide topic and h e nce w il


l
notbe cove re d be yond bas ic cl as s de claration and obje ct
ins tantiation s yntax.

//class Declaration
class className [extends parentClassname] {
var $attribute;
//constructor
function className([$params]){statement;}
//member function
function functionName([$params]){statements;}
}
//class instantiation
$ob = new className();
//calling a member function
$result = $ob->functionName();

Type functions

Som e us e fulfunctions for de al ing w ith type s are th e


var_ dum p(), ge ttype () and is _ * functions . Th e var_ dum p
function re curs ive l y dum ps th e e ntire variabl e pas s e d in,
incl uding th e type s ofth e variabl e and al lits m e m be rs (for
obje cts ) and e le m e nts (for arrays ). Th e ge ttype function re turns
th e type ofth e variabl e pas s e d in and th e is _ * functions te s tifa
variabl e is ofa ce rtain type .

For m ore inform ation aboutPH P data type s , pl e as e re fe r to


"h ttp://ph p.ne t/m anual
/e n/l
anguage .type s .ph p".

Pos t, Ge t, Se s s ion and Databas e s


Since PH P is m os tcom m onl y us e d to program w e b
appl ications , itre q uire s w ays to obtain data from th e us e r
th rough H TTP PO ST and GET m e th ods as w e l las w ays to
m aintain coh e re nts e s s ions for us e rs . Final
ly, m os tw e b
appl ications re q uire w ays to s tore us e r-s ubm itte d data.

Us e fulSupe rgl
obal
s

Al lPO ST variabl e s m ay be obtaine d from an array cal led


$_ PO ST and al lGET variabl e s from th e $_ GET array. Th e s e
variabl e s are cal le d s upe rgl
obalvariabl e s , w h ich m e ans th at
th e y are autom atical ly global. PH P provide s a fe w oth e r us e ful
s upe rgl obal s , incl uding $_ CO O K IE for cook ie s and $_ FILES for
upl oade d files.

Se s s ion H andl
ing

To s tarta s e s s ion, th e s e s s ion_ s tart() function m us tbe cal l


ed
be fore any oth e r outputis s e ntto th e brow s e r, afte r w h ich th e
$_ SESSIO N s upe rgl obalm ay be us e d to s tore al ls e s s ion
variabl e s . Subs e q ue ntl y, al lpage s th atform a partofth e
s e s s ion m us tal s o cal lth e s e s s ion_ s tart() function. To e nd a
s e s s ion, th e s e s s ion_ de s troy() function is cal l
e d.
H andl
ing Databas e s

PH P h as l
ibrarie s for inte rfacing w ith m os tofth e popul ar
re l
ationaldatabas e s e rve rs in us e today. Th e s e incl ude
M ySQL, Pos tgre SQL, O racl e and M S SQL. Itis be yond th e
s cope ofth is prim e r to e xh aus tive l
y e xpl
ore th e rich l
ibrarie s of
functions provide d by PH P to acce s s th e s e databas e s .

H ow e ve r, one ofth e m os tus e fulfe ature s aboutPH P is th atit


trie s to provide a m ore or l e s s cons is te nts uite ofs im il
arl y-
nam e d functions th atare val id for m os tdatabas e s . For
ins tance , to conne ctto a databas e s e rve r, one w oul d us e a
*_ conne ct() function, w h e re * is re pl ace d by th e type ofs e rve r.
For a M ySQLs e rve r, one w oul d us e m ys q l_ conne ct(), for a M S
SQLs e rve r, one w oul d us e m s s q l_ conne ct() and s o on.

Th e functions us e d to q ue ry databas e s are nots o cons is te ntl y


nam e d, butafte r a q ue ry h as be e n e xe cute d, one w oul d us e
th e *_ fe tch _ as s oc(), *_ fe tch _ array() and *_ fe tch _ row ()
functions to re trie ve th e data from th e q ue rie s . Final l
y, to cl os e
th e conne ction to th e databas e , one w oul d cal lth e *_ clos e ()
function.

ControlStructure s and O pe rators


In m os tprogram m ing tutorial s , th e s e w oul
d be introduce d
e arlie r in th e docum e nt. H ow e ve r, s ince th is prim e r is prim aril
y
m e antfor program m e rs w h o are ne w to PH P, and al s o due to
th e factth atth e s yntax ofth e s e l anguage cons tructs in PH P
are s im il ar to th e ir counte rparts in oth e r l anguage s , w e h ave
ch os e n provide onl y brie fs um m arie s ofth e m atth e e nd ofth is
docum e nt.
Conditional
s

if-e l
s e if-e l
se:

if (condition){ statement;}
//yes, elseif is one word
elseif(condition){ statement; }
else{ statement; }

s w itch cas e :

switch (expression){
case constant1: statement; break;
case constant2: statement; break;
default: statement; break;
}

Ite ration

w h il
e l
oop:
while(condition){ statement; }

for l
oop:
for(init expr; terminate expr; iterate
expr){ statement; }

foreach loop:
foreach($array as $val){ statement; }
or
foreach($array as $key=>$val){ statement; }
O pe rators (de cre as ing pre ce de nce )

O pe rators AdditionalInform ation


new ne w
[] array()
++ -- incre m e nt/de cre m e nt
instanceof type s
! logical
* / % arith m e tic
+ - . arith m e tic and s tring
<< >> bitw is e
< <= > >= com paris on
== != com paris on
=== !== com paris on
& bitw is e and re fe re nce s
^ bitw is e
| bitw is e
&& logical
|| logical
? : te rnary
= += -= *= /= as s ignm e nt
.= %= &= |= as s ignm e nt
^= <<= >>= as s ignm e nt
and logical
xor logical
or logical

PH P Prim e r v0.1
Cre ate d by: Adrian Que k and Ch in Yong, Singapore PH P
Us e r Group (w w w .ph p.com .s g)
Copyrigh t: 22 Fe b 2008 GNU FDL,
(w w w .gnu.org/copyl e ft/fdl
.h tm l
)

W ith k ind s upportfrom Abl


e w is e .com