E-book – Endang Cahya Permana

I n t r odu ct ion t o
Obj e ct - or ie n t e d
pr ogr a m m in g w it h PH P
Marcus Börger

PH P Qu e be c con fe r e n ce 2 0 0 7

Overview
;

What is OOP?

;

PHP and OOP

;

Except ions

;


I t erat ors

;

Reflect ion

;

Pat t erns
Marcus Börger

Introduction to Object-oriented programming with PHP

2

What is OOP
c l as s Us el es s ex t ends Nons ens e
{
abs t r ac t f unc t i on bl aBl a( ) ;

}

?

Marcus Börger

Introduction to Object-oriented programming with PHP

3

What does OOP aim t o
achieve?
;
;
;
;
;
;

Allow com part m ent alized refact oring of code.

Prom ot e code re- use.
Prom ot e ext ensibilit y, flexibilit y and adapt abilit y.
Bet t er for t eam developm ent .
Many pat t erns are designed for OOP.
Som e pat t erns lead t o m uch m ore efficient code.

;

Do you need t o use OOP t o achieve t hese goals?
; Of course not .
; I t ’s designed t o m ake t hose t hings easier t hough.

Marcus Börger

Introduction to Object-oriented programming with PHP

4

What are t he feat ures of
OOP?

;

Encapsulat ion

;

I nherit ance

;

Polym orphism

Marcus Börger

Introduction to Object-oriented programming with PHP

5

Encapsulat ion
;


Encapsulat ion is about grouping of funct ionalit y
( operat ions) and relat ed dat a ( at t ribut es) t oget her
int o a coherent dat a st ruct ure ( classes) .

Marcus Börger

Introduction to Object-oriented programming with PHP

6

Encapsulat ion
;

;

Encapsulat ion is about grouping of funct ionalit y
( operat ions) and relat ed dat a ( at t ribut es) t oget her
int o a coherent dat a st ruct ure ( classes) .
Classes represent com plex dat a t ypes and t he

operat ions t hat act on t hem . An obj ect is a
part icular inst ance of a class.

Marcus Börger

Introduction to Object-oriented programming with PHP

7

Encapsulat ion
;

;

;

Encapsulat ion is about grouping of funct ionalit y
( operat ions) and relat ed dat a ( at t ribut es) t oget her
int o a coherent dat a st ruct ure ( classes) .
Classes represent com plex dat a t ypes and t he

operat ions t hat act on t hem . An obj ect is a
part icular inst ance of a class.
The basic idea is t o re- code real life.
For inst ance, if you press a key on your lapt op keyboard
you do not know what is happening in det ail. For you it is
t he sam e as if you press t he keyboard of an ATM. We say
t he int erface is t he sam e. I f anot her person has t he sam e
lapt op t he int ernal det ails w ould be exact ly t he sam e.

Marcus Börger

Introduction to Object-oriented programming with PHP

8

Encapsulat ion
;

;


;

Encapsulat ion is about grouping of funct ionalit y
( operat ions) and relat ed dat a ( at t ribut es) t oget her
int o a coherent dat a st ruct ure ( classes) .
Classes represent com plex dat a t ypes and t he
operat ions t hat act on t hem . An obj ect is a
part icular inst ance of a class.
The basic idea is t o re- code real life.
For inst ance, if you publish a t ext t hat is not really different
from publishing a pict ure. Bot h are cont ent t ypes and you
m ight want t o encapsulat e t he det ails on how t o do t he
act ual publishing in a class. And once you have t hat you
can easily have cont ent t hat consist s of bot h pict ures and
t ext and yet use t he sam e operat ions for publishing. Then
lat er you m ight publish t ables using t he sam e int erface.
Marcus Börger

Introduction to Object-oriented programming with PHP


9

Encapsulat ion: Are Obj ect s
Just Dict ionaries?
;

I n PHP 4 obj ect s were lit t le m ore t han arrays.

;

I n PHP 5 you get m uch m ore cont rol by visibilit y,
int erfaces, t ype hint s, int ercept ors and m ore.

;

Anot her difference is coherency. Classes can be
t old t o aut om at ically execut e specific code on
obj ect creat ion and dest ruct ion.
c l as s Si mpl e {
f unc t i on __c ons t r uc t ( ) { / * . . . * / }

f unc t i on __des t r uc t ( ) { / * . . . * / }
}
Marcus Börger

Introduction to Object-oriented programming with PHP

10

Dat a Hiding
;

Anot her difference bet ween obj ect s and arrays is
t hat obj ect s perm it st rict visibilit y sem ant ics. Dat a
hiding eases refact oring by cont rolling what ot her
part ies can access in your code.
;
;
;
;
;


public
prot ect ed
privat e
final
abst ract

anyone can access it
only descendant s can access it
only you can access it
no one can re- declare it
som eone else will im plem ent t his

Why have t hese in PHP?
Because som et im es self- discipline isn’t enough.
Marcus Börger

Introduction to Object-oriented programming with PHP

11

I nherit ance
;

I nherit ance allows a class t o specialize ( or ext end)
anot her class and inherit all it s m et hods,
propert ies and behaviors.

;

This prom ot es
;
;
;
;
;

Ext ensibilit y
Reusabilit y
Code Consolidat ion
Abst ract ion
Responsibilit y

Marcus Börger

Introduction to Object-oriented programming with PHP

12

The Problem of Code
Duplicat ion
;

Code duplicat ion cont radict s m aint ainabilit y.
You oft en end up wit h code t hat looks like t his:
f unc t i on f oo_t o_x ml ( $f oo) {
/ / gener i c s t uf f
/ / f oo- s pec i f i c s t uf f
}
f unc t i on bar _t o_x ml ( $bar ) {
/ / gener i c s t uf f
/ / bar s pec i f i c s t uf f
}

Marcus Börger

Introduction to Object-oriented programming with PHP

13

The Problem of Code
Duplicat ion
;

You could clean t hat up as follows
f unc t i on bas e_t o_x ml ( $dat a) { / * . . . * / }
f unc t i on f oo_t o_x ml ( $f oo) {
bas e_t o_x ml ( $f oo) ;
/ / f oo s pec i f i c s t uf f
}
f unc t i on bar _t o_x ml ( $bar ) {
bas e_t o_x ml ( $bar ) ;
/ / bar s pec i f i c s t uf f
}

;

But it ’s hard t o keep base_t o_xm l( ) working for
t he disparat e foo and bar t ypes.

Marcus Börger

Introduction to Object-oriented programming with PHP

14

The Problem of Code
Duplicat ion
;

;

I n an OOP st yle you would creat e classes for t he
Foo and Bar classes t hat ext end from a base class
t hat handles com m on funct ionalit y.
Sharing a base class prom ot es sam eness.
c l as s Bas e {
publ i c f unc t i on t oXML( )
{
/ *. . . */
}
}
c l as s Foo ex t ends Bas e {
publ i c f unc t i on t oXML( )
{
par ent : : t oXML( ) ;
/ / f oo s pec i f i c s t uf f
}
}

Marcus Börger

c l as s Bar ex t ends Bas e {
publ i c f unc t i on t oXML( )
{
par ent : : t oXML( ) ;
/ / bar s pec i f i c s t uf f
}
}

Introduction to Object-oriented programming with PHP

15

Polym orphism ?
;

Suppose a calendar t hat is a collect ion of ent ries.
Procedurally dislpaying all t he ent ries m ight look like:
f or eac h( $ent r i es as $ent r y) {
s wi t c h( $ent r y[ ’ t y pe’ ] ) {
c as e ' pr of es s i onal ' :
di s pl ay _pr of es s i onal _ent r y( $ent r y) ;
br eak ;
c as e ' per s onal ' :
di s pl ay _per s onal _ent r y( $ent r y) ;
br eak ;
}
}

Marcus Börger

Introduction to Object-oriented programming with PHP

16

Sim plicit y t hrough
Polym orphism
;

I n t he OOP paradigm t his would look like:
f or eac h( $ent r i es as $ent r y) {
$ent r y- >di s pl ay( ) ;
}

;

The key point is we don't have t o m odify t his loop
t o add new t ypes. When we add a new t ype, t hat
t ype get s a display( ) m et hod so t hat it knows how
t o display it self, and we’re done.

;

Also t his is m uch fast er because we do not have t o
check t he t ype for every elem ent .
Marcus Börger

Introduction to Object-oriented programming with PHP

17

Sim plicit y t hrough Magic?
;

Act ually in PHP you m ight want t his:
f or eac h( $ent r i es as $ent r y) {
ec ho $ent r y;
}

;

A class can have a __t oSt r i ng( ) m et hod which
defines how it s obj ect s are convert ed int o a
t ext ual represent at ion.

;

PHP 5.2 support s t his in all st ring cont ext s.

Marcus Börger

Introduction to Object-oriented programming with PHP

18

Polym orphism
t he ot her way round
;

;

Unlike ot her languages PHP does not and will not
offer polym orphism for m et hod calling. Thus t he
following will never be available in PHP
< ?php
class Test {
funct ion t oXML( Personal $obj ) / / …
funct ion t oXML( Professional $obj ) / / …
}
?>
To work around t his
; Use t he ot her way round ( call ot her m et hods from a
single t oXML( ) funct ion in a polym orphic way)
; Use swit ch/ case ( t hough t his is not t he OO way)

Marcus Börger

Introduction to Object-oriented programming with PHP

19

Anot her exam ple
c l as s Humans {
publ i c f unc t
/ *. . . */
}
publ i c f unc t
publ i c f unc t
publ i c f unc t
publ i c f unc t
}

Marcus Börger

i on __c ons t r uc t ( $name) {

i
i
i
i

on
on
on
on

eat ( ) { / * .
s l eep( ) { /
s nor e( ) { /
wak eup( ) {

. . */
*. . .
*. . .
/ *. .

}
*/ }
*/ }
. */ }

Introduction to Object-oriented programming with PHP

20

Som e I nherit ance
c l as s Humans {
publ i c f unc t i on
publ i c f unc t i on
publ i c f unc t i on
publ i c f unc t i on
publ i c f unc t i on
}
c l as s Women ex t ends
publ i c f unc t i on
}

Marcus Börger

__c ons t r uc t
eat ( ) { / * .
s l eep( ) { /
s nor e( ) { /
wak eup( ) {

( $name) { / * . . . * / }
. . */ }
*. . . */ }
*. . . */ }
/ *. . . */ }

Humans {
gi v eBi r t h( ) { / * . . . * / }

Introduction to Object-oriented programming with PHP

21

I nherit ance+ Polym orphism
c l as s Humans {
publ i c f unc t i on __c ons t r uc t ( $name) { / * . . . * / }
publ i c f unc t i on eat ( ) { / * . . . * / }
publ i c f unc t i on s l eep( ) { / * . . . * / }
publ i c f unc t i on wak eup( ) { / * . . . * / }
}
c l as s Women ex t ends Humans {
publ i c f unc t i on gi v eBi r t h( ) { / * . . . * / }
}
c l as s Men ex t ends Humans {
publ i c f unc t i on s nor e( ) { / * . . . * / }
}

Marcus Börger

Introduction to Object-oriented programming with PHP

22

A lit t le abst ract ion
abs t r ac t c l as s Humans {
publ i c f unc t i on __c ons t r uc t ( $name) { / * . . . * / }
abs t r ac t publ i c f unc t i on gender ( ) ;
publ i c f unc t i on eat ( ) { / * . . . * / }
publ i c f unc t i on s l eep( ) { / * . . . * / }
publ i c f unc t i on wak eup( ) { / * . . . * / }
}
c l as s Women ex t ends Humans {
publ i c f unc t i on gender ( ) { r et ur n ' f emal e' ; }
publ i c f unc t i on gi v eBi r t h( ) { / * . . . * / }
}
c l as s Men ex t ends Humans {
publ i c f unc t i on gender ( ) { r et ur n ' mal e' ; }
publ i c f unc t i on s nor e( ) { / * . . . * / }
}

Marcus Börger

Introduction to Object-oriented programming with PHP

23

A lit t le abst ract ion
abs t r ac t c l as s Humans {
publ i c f unc t i on __c ons t r uc t ( $name) { / * . . . * / }
abs t r ac t publ i c f unc t i on gender ( ) ;
publ i c f unc t i on eat ( ) { / * . . . * / }
publ i c f unc t i on s l eep( ) { / * . . . * / }
publ i c f unc t i on wak eup( ) { / * . . . * / }
}
c l as s Women ex t ends Humans {
f i nal publ i c f unc t i on gender ( ) { r et ur n ' f ' ; }
publ i c f unc t i on gi v eBi r t h( ) { / * . . . * / }
}
c l as s Men ex t ends Humans {
f i nal publ i c f unc t i on gender ( ) { r et ur n ' m' ; }
publ i c f unc t i on s nor e( ) { / * . . . * / }
}

Marcus Börger

Introduction to Object-oriented programming with PHP

24

PH P a n d OOP

Marcus Börger

Introduction to Object-oriented programming with PHP

25

PHP 4 and OOP ?
Š

Poor Obj ect m odel
; Met hods
: No visibilit y
: No abst ract s, no final
: St at ic wit hout declarat ion

; Propert ies
: No st at ic propert ies
: No const ant s

; I nherit ance
: No abst ract , final inherit ance, no int erfaces
: No prot ot ype checking, no t ypes

; Obj ect handling
: Copied by value
: No dest ruct ors

Marcus Börger

Introduction to Object-oriented programming with PHP

26

ZE2's revam ped obj ect m odel
;
;
;
;
;
;
;
;
;
;
;

Obj ect s are referenced by ident ifiers
Const ruct ors and Dest ruct ors
St at ic m em bers
Const ant s
Visibilit y
I nt erfaces
Final and abst ract m em bers
I nt ercept ors
Except ions
Reflect ion API
I t erat ors
Marcus Börger

Introduction to Object-oriented programming with PHP

27

Revam ped Obj ect Model
;

PHP 5 has really good OOP support
;
;
;
;
;

Bet t er code reuse
Bet t er for t eam developm ent
Easier t o refact or
Som e pat t erns lead t o m uch m ore efficient code
Fit s bet t er in m arket ing scenarios

Marcus Börger

Introduction to Object-oriented programming with PHP

28

PH P 5 OOP in de t a il

Marcus Börger

Introduction to Object-oriented programming with PHP

29

Obj ect s referenced by
ident ifiers
;
;
;

Obj ect s are no longer som ewhat special arrays
Obj ect s are no longer copied by default
Obj ect s m ay be copied using clone/ __clone( )
c l as s Obj ec t { } ;

$obj

$ref

$dup

$obj = new Obj ec t ( ) ;
Instance 1

Instance 2

$r ef = $obj ;
$dup = c l one $obj ;

Marcus Börger

Class Object

Introduction to Object-oriented programming with PHP

30

Const ruct ors and Dest ruct ors
;

Const ruct ors/ Dest ruct ors cont rol obj ect lifet im e
; Const ruct ors m ay have bot h new OR old st yle nam e
; New st yle const ruct ors are preferred
; Const ruct ors m ust not use inherit ed prot ocol

; Dest ruct ors are called when delet ing t he last reference
; No part icular or cont rollable order during shut down
; Dest ruct ors cannot have param et ers
; Since PHP 5.0.1 dest ruct ors can work w it h resources
c l as s Obj ec t {
f unc t i on __c ons t r uc t ( ) { }
f unc t i on __des t r uc t ( ) { }
}
$obj = new Obj ec t ( ) ;
uns et ( $obj ) ;
Marcus Börger

Introduction to Object-oriented programming with PHP

31

Const ruct ors and Dest ruct ors
;

Parent s m ust be called m anually
c l as s Bas e {
f unc t i on __c ons t r uc t ( ) { }
f unc t i on __des t r uc t ( ) { }
}
c l as s Obj ec t ex t ends Bas e {
f unc t i on __c ons t r uc t ( ) {
par ent : : __c ons t r uc t ( ) ;
}
f unc t i on __des t r uc t ( ) {
par ent : : __des t r uc t ( ) ;
}
}
$obj = new Obj ec t ( ) ;
uns et ( $obj ) ;

Marcus Börger

Introduction to Object-oriented programming with PHP

32

Default propert y values
;

Propert ies can have default values
; Bound t o t he class not t o t he obj ect
; Default values cannot be changed but overw rit t en
c l as s Obj ec t {
v ar $pr op = " Hel l o\ n" ;
}
$obj 1 = new Obj ec t ;
$obj 1- >pr op = " Hel l o Wor l d\ n" ;
$obj 2 = new Obj ec t ;
ec ho $obj 2- >pr op; / / Hel l o

Marcus Börger

$obj1

$obj2

Instance 1
$prop

Instance 2
$prop

Class Object
$prop/default

Introduction to Object-oriented programming with PHP

33

St at ic m em bers
;

St at ic m et hods and propert ies
; Bound t o t he class not t o t he obj ect
; Only exist s once per class rat her t han per inst ance

; Can be init ialized
c l as s Obj ec t {
v ar $pr op;
s t at i c $s t at
s t at i c f unc t i
ec ho s el f : :
}
}
Obj ec t : : t es t ( ) ;
$obj 1 = new Obj
$obj 2 = new Obj
Marcus Börger

= " Hel l o\ n" ;
on t es t ( ) {
$s t at ;

$obj1

$obj2

Instance 1
$prop

Instance 2
$prop

Class Object
$stat

ec t ;
ec t ;
Introduction to Object-oriented programming with PHP

34

Pseudo const ant s
;
;
;
;
;

__CLASS__
__METHOD__
s el f
par ent
$t hi s

shows t he current class nam e
shows class and m et hod or funct ion
references t he class it self
references t he parent class
references t he obj ect it self

c l as s Bas e {
s t at i c f unc t i on Show( ) {
ec ho __FI LE__. ' ( ' . __LI NE__. ' ) : ' . __METHOD__. " \ n" ;
}
}
c l as s Obj ec t ex t ends Bas e {
s t at i c f unc t i on Us e( ) {
Sel f : : Show( ) ;
Par ent : : Show( ) ;
}
s t at i c f unc t i on Show( ) {
ec ho __FI LE__. ' ( ' . __LI NE__. ' ) : ' . __METHOD__. " \ n" ;
}
}
Marcus Börger

Introduction to Object-oriented programming with PHP

35

Visibilit y
;

Cont rolling m em ber visibilit y / I nform at ion hiding
; A derived class doesn't know parent s privat e m em bers
; An inherit ed prot ect ed m em ber can be m ade public
c l as s Bas e {
publ i c $a;
pr ot ec t ed $b;
pr i v at e $c ;
}
c l as s Der i v ed ex t ends Bas e {
publ i c $a;
publ i c $b;
pr i v at e $c ;
}

Marcus Börger

Derived
Base
$a
$b
$c
$a
$b
$c
Base::$c

Introduction to Object-oriented programming with PHP

36

Const ruct or visibilit y
;

A prot ect ed const ruct or prevent s inst ant iat ion
c l as s Bas e {
pr ot ec t ed f unc t i on __c ons t r uc t ( ) {
}
}
c l as s Der i v ed ex t ends Bas e {
/ / c ons t r uc t or i s s t i l l pr ot ec t ed
s t at i c f unc t i on get Bas e( ) {
r et ur n new Bas e; / / Fac t or y pat t er n
}
}
c l as s Thr ee ex t ends Der i v ed {
publ i c f unc t i on __c ons t r uc t ( ) {
}
}
Marcus Börger

Introduction to Object-oriented programming with PHP

37

The Singlet on pat t ern
;

Som et im es you want only a single inst ance of
aclass t o ever exist .
; DB connect ions
; An obj ect represent ing t he user or connect ion.
c l as s Si ngl et on {
s t at i c pr i v at e $i ns t anc e;
pr ot ec t ed f unc t i on __c ons t r uc t ( ) { }
f i nal pr i v at e f unc t i on __c l one( ) { }
s t at i c f unc t i on get I ns t anc e( ) {
i f ( ! s el f : : $i ns t anc e)
s el f : : $i ns t anc e = new Si ngl et on( ) ;
r et ur n s el f : : $i ns t anc e;
}
}
$a = Si ngl et on: : get I ns t anc e( ) ;
$a- >i d = 1;
$b = Si ngl et on: : get I ns t anc e( ) ;
pr i nt $b- >i d. " \ n" ;
Marcus Börger

Introduction to Object-oriented programming with PHP

38

Const ant s
;
;

Const ant s are read only st at ic propert ies
Const ant s are always public
c l as s Bas e {
c ons t gr eet i ng = " Hel l o\ n" ;
}
c l as s Der v i ed ex t ends Bas e {
c ons t gr eet i ng = " Hel l o Wor l d\ n" ;
s t at i c f unc t i on f unc ( ) {
ec ho par ent : : gr eet i ng;
}
}
ec ho Bas e: : gr eet i ng;
ec ho Der i v ed: : gr eet i ng;
Der i v ed: : f unc ( ) ;
Marcus Börger

Introduction to Object-oriented programming with PHP

39

Abst ract m em bers
;

Met hods can be abst ract
; They don’t have a body
; A class wit h an abst ract m et hod m ust be abst ract

;

Classes can be m ade abst ract
; The class cannot be inst ant iat ed

;

Propert ies cannot be m ade abst ract
abs t r ac t c l as s Bas e {
abs t r ac t f unc t i on no_body ( ) ;
}
c l as s Der i v ed ex t ends Bas e {
f unc t i on no_body ( ) { ec ho " Body \ n" ; }
}

Marcus Börger

Introduction to Object-oriented programming with PHP

40

Final m em bers
;

Met hods can be final
; They cannot be overwrit t en
; They are class invariant s

;

Classes can be final
; They cannot be inherit ed
c l as s Bas e {
f i nal f unc t i on i nv ar i ant ( ) { ec ho " Hel l o\ n" ; }
}
c l as s Der i v ed ex t ends Bas e {
}
f i nal c l as s Leaf ex t ends Der i v ed {
}

Marcus Börger

Introduction to Object-oriented programming with PHP

41

;

Different Obj ect
sam e behavior

Oft en different obj ect s have t he sam e int erface
wit hout having t he sam e base class
c l as s Li ne {
f unct i on dr aw( ) { } ;
}
c l as s Pol ygon {
pr ot ect ed $l i nes;
f unct i on dr aw( ) {
f or each( $t hi s- >l i nes as $l i ne)
$l i ne- >dr aw( ) ;
}
}
c l as s Rect angl e ext ends Pol ygon {
}
c l as s El l i pse {
f unct i on dr aw( ) { } ;
}
c l as s Ci r c l e ex t ends El l i pse {
f unct i on dr aw( ) {
par ent : : dr aw( ) ;
}
}

Marcus Börger

Line

Ellipse

$lines
Polygon

Circle

Rectangle

Introduction to Object-oriented programming with PHP

42

I nt erfaces
;
;

I nt erfaces describe an abst ract class prot ocol
Classes m ay inherit m ult iple I nt erfaces
i nt er f ace Dr awabl e {
f unct i on dr aw( ) ;
}
c l as s Li ne i mpl ement s Dr awabl e {
f unct i on dr aw( ) { } ;
}
c l as s Pol ygon i mpl ement s Dr awabl e {
pr ot ect ed $l i nes;
f unct i on dr aw( ) {
f or each( $t hi s- >l i nes as $l i ne)
$l i ne- >dr aw( ) ;
}
}
c l as s Rect angl e ext ends Pol ygon {
}
c l as s El l i pse i mpl ement s Dr awabl e {
f unct i on dr aw( ) { } ;
}
c l as s Ci r c l e ex t ends El l i pse {
f unct i on dr aw( ) {
par ent : : dr aw( ) ;
}
}

Marcus Börger

Drawable

Line

Ellipse

$lines
Polygon

Circle

Rectangle

Introduction to Object-oriented programming with PHP

43

Propert y kinds
;

Declared propert ies
; May have a default value
; Can have select ed visibilit y

;

I m plicit public propert ies
; Declared by sim ply using t hem in ANY m et hod

;

Virt ual propert ies
; Handled by int ercept or m et hods

;

St at ic propert ies
; Bound t o t he class rat her t han t o t he inst ance

Marcus Börger

Introduction to Object-oriented programming with PHP

44

Obj ect t o St ring conversion
;

__t oSt ring( ) : sem i- aut om at ic obj ect t o st ring
conversion wit h echo and print
( aut om at ic st art ing wit h 5.2)
c l as s Obj ec t {
f unc t i on __t oSt r i ng( ) {
r et ur n ' Obj ec t as s t r i ng' ;
}
}
$o = new Obj ec t ;
ec ho $o;

/ / does c al l __t oSt r i ng

$s t r = ( s t r i ng) $o; / / does c al l __t oSt r i ng

Marcus Börger

Introduction to Object-oriented programming with PHP

45

I nt ercept ors
;

Allow t o dynam ically handle non class m em bers
; Lazy init ializat ion of propert ies
; Sim ulat ing Obj ect aggregat ion and Mult iple inherit ance
c l as s Obj ec t {
pr ot ec t ed $v i r t ual = ar r ay( ) ;
f unc t i on __get ( $name) {
r et ur n @$t hi s - >v i r t ual [ $name] ;
}
f unc t i on __s et ( $name, $v al ue) {
$t hi s - >v i r t ual [ $name] = $v al ue;
}
f unc t i on __uns et ( $name) {
uns et ( $t hi s - >v i r t ual [ $name] ) ;
}
f unc t i on __i s s et ( $name) {
r et ur n i s s et ( $t hi s - >v i r t ual [ $name] ) ;
}
f unc t i on __c al l ( $f unc , $par ams) {
ec ho ' Coul d not c al l ' . __CLASS__ . ' : : '
}
}
Marcus Börger

. $f unc . " \ n" ;

Introduction to Object-oriented programming with PHP

46

Typehint ing
;

PHP 5 allows t o easily force a t ype of a param et er
;
;
;
;

PHP does not allow NULL for t ypehint s
Typehint s m ust be inherit ed as given in base class
PHP 5.1 offers t ypehint ing wit h arrays
PHP 5.2 offers opt ional t ypehint ed param et ers ( = NULL)

c l as s Obj ec t {
publ i c f unc t i on c ompar e( Obj ec t $ot her ) {
/ / Some c ode her e
}
publ i c f unc t i on c ompar e2( $ot her ) {
i f ( i s _nul l ( $ot her ) | | $ot her i ns t anc eof Obj ec t ) {
/ / Some c ode her e
}
}
}

Marcus Börger

Introduction to Object-oriented programming with PHP

47

Class Design
;

I t is im port ant t o t hink about your class hierarchy

;

Avoid very deep or broad inherit ance graphs

;

PHP only support s is- a and has- a relat ions
Tires

Bicycle
Vehicle
Car

Marcus Börger

Bus

Engine
Truck

Diesel

Tank

Turbine

Gasoline
Plane

Introduction to Object-oriented programming with PHP

48

Too St rict or t oo Weak?
;

PHP t ries t o prevent you from doing som e errors
; You are bound t o keep inherit ed signat ures
; You cannot change from ref t o non- ref ret urn

;

Yet PHP allows absolut e flexibilit y
; Just do not define a signat ure
; Warning: This is ext rem ely error prone

Marcus Börger

Introduction to Object-oriented programming with PHP

49

D yn a m ic cla ss loa din g

Marcus Börger

Introduction to Object-oriented programming with PHP

50

Dynam ic class loading
;

__aut ol oad( ) is good when you're alone
; Requires a single file for each class
; Only load class files when necessary
; No need t o parse/ com pile unneeded classes
; No need t o check which class files t o load

: Addit ional user space code
1 Only one single loader m odel is possible

Marcus Börger

Introduction to Object-oriented programming with PHP

51

__aut ol oad & r equi r e_onc e
;

St or e t he c l as s l oader i n an i nc l ude f i l e
; I n eac h s c r i pt :
r equi r e_onc e( ' / aut ol oad. i nc ' )
; Us e I NI opt i on:
aut o_pr epend_f i l e=/ aut ol oad. i nc


Marcus Börger

Introduction to Object-oriented programming with PHP

52

SPL's class loading
;

Support s fast default im plem ent at ion
; Look int o pat h's specified by I NI opt ion include_pat h
; Look for specified file ext ensions ( .inc, .php)

;

Abilit y t o regist er m ult iple user defined loaders

;

Overwrit es ZEND engine's __aut oload( ) cache
; You need t o regist er __aut oload if using spl's aut oload

Marcus Börger

Introduction to Object-oriented programming with PHP

53

SPL's class loading
;

;
;
;
;
;

s pl _aut ol oad( $c l as s _name, $ex t ens i ons=NULL)
Load a class from a file in include pat h
Fast c code im plem ent at ion
s pl _aut ol oad_ex t ens i ons( $ex t ens i ons=NULL)
Get or set filenam e ext ensions
s pl _aut ol oad_r egi s t er ( $l oader _f unc t i on)
Regist er a single loader funct ion
s pl _aut ol oad_unr egi s t er ( $l oader _f unc t i on)
Unregist er a single loader funct ion
s pl _aut ol oad_f unc t i ons( )
List all regist ered loader funct ions
s pl _aut ol oad_c al l ( $c l as s _name)
Load a class t hrough regist ered class loaders
Uses s pl _aut ol oad( ) as fallback
Marcus Börger

Introduction to Object-oriented programming with PHP

54

Ex ce pt ion s

Marcus Börger

Introduction to Object-oriented programming with PHP

55

Except ions
;

Respect t hese rules
1. Except ions are except ions
2. Never use except ions for cont rol flow
3. Never ever use except ions for param et er passing


Marcus Börger

Introduction to Object-oriented programming with PHP

56

Except ion specializat ion
;
;

Except ions should be specialized
Except ions should inherit built in class except ion
c l as s Your Ex c ept i on ex t ends Ex c ept i on {
}
try {
/ / y our c ode
t hr ow new Your Ex c ept i on( ) ;
}
c at c h ( Your Ex c ept i on $e) {
/ / ex c ept i on handl i ng
}
c at c h ( Ex c ept i on $e) {
/ / ex c ept i on handl i ng
}
Marcus Börger

Introduction to Object-oriented programming with PHP

57

Except ion specializat ion
;
;

Except ion blocks can be nest ed
Except ions can be re t hrown
c l as s Your Ex c ept i on ex t ends Ex c ept i on { }
try {
try {
/ / y our c ode
t hr ow new Your Ex c ept i on( ) ;
}
c at c h ( Your Ex c ept i on $e) {
/ / ex c ept i on handl i ng
t hr ow $e;
}
c at c h ( Ex c ept i on $e) {
/ / ex c ept i on handl i ng
}
}
c at c h ( Your Ex c ept i on $e) {
/ / ex c ept i on handl i ng
}

Marcus Börger

Introduction to Object-oriented programming with PHP

58

Pract ical use of except ions
;

Const ruct or failure

;

Convert ing errors/ warnings t o except ions

;

Sim plify error handling

;

Provide addit ional error inform at ion by t agging

Marcus Börger

Introduction to Object-oriented programming with PHP

59

Const ruct or failure
;
;

I n PHP 4.4 you would sim ply uns et ( $t hi s)
Provide an argum ent t o receive t he error condit ion

Marcus Börger

Introduction to Object-oriented programming with PHP

60

Const ruct or failure
;
;

I n 5 const ruct ors do not ret urn t he creat ed obj ect
Except ions allow t o handle failed const ruct ors

Marcus Börger

Introduction to Object-oriented programming with PHP

61

Convert Errors t o Except ions
;

I m plem ent ing PHP 5.1 class ErrorExcept ion

Marcus Börger

Introduction to Object-oriented programming with PHP

62

Convert Errors t o Except ions
;

I m plem ent ing t he error handler


Marcus Börger

Introduction to Object-oriented programming with PHP

63

Sim plify error handling
;

Typical dat abase access code cont ains lot s of if's



Marcus Börger

Introduction to Object-oriented programming with PHP

64

Sim plify error handling
;

Trade code sim plicit y wit h a new com plexit y



Marcus Börger

Introduction to Object-oriented programming with PHP

65

SPL Except ions
;
;

SPL provides a st andard set of except ions
Class Except ion m ust be t he root of all except ions

Marcus Börger

Introduction to Object-oriented programming with PHP

66

General dist inguishing
;

Logi c Ex c ept i on
Î Anyt hing t hat could have been det ect ed at
com pile t im e, during applicat ion design
or by t he good old t echnology:
" look closely"

;

Runt i meEx c ept i on
Î Anyt hing t hat is unexpect ed during runt im e
Î Base Except ion for all dat abase ext ensions

Marcus Börger

Introduction to Object-oriented programming with PHP

67

LogicExcept ion

;

Funct ion not found or sim ilar
BadMet hodCal l Ex c ept i on

;

Value not in allowed dom ain

;

Argum ent not valid

;

Lengt h exceeded

;

Som e index is out of range
Marcus Börger

Introduction to Object-oriented programming with PHP

68

RunTim eExcept ion

;

An act ual value is out of bounds

;

Buffer or ot her overflow sit uat ion

;

Value out side expect ed range

;

Buffer or ot her underflow sit uat ion

;

Any ot her unexpect ed values
Marcus Börger

Introduction to Object-oriented programming with PHP

69

Overloading __call
;

I f using __call, ensure only valid calls are m ade
abs t r ac t c l as s My I t er at or Wr apper i mpl ement s I t er at or
{
f unc t i on __c ons t r uc t ( I t er at or $i t )
{
Compile-Time:
$t hi s - >i t = $i t ;
}
Error in design
f unc t i on __c al l ( $f unc , $ar gs)
{
$c al l ee = ar r ay ( $t hi s - >i t , $f unc) ;
i f ( ! i s _c al l abl e( $c al l ee) ) {
t hr ow new BadMet hodCal l Ex c ept i on( ) ;
}
r et ur n c al l _us er _f unc _ar r ay( $c al l ee, $ar gs) ;
}
}

Marcus Börger

Introduction to Object-oriented programming with PHP

70

I nt erfaces and __call
;
;

I nt erface funct ions cannot be handled by __call
Eit her m ark t he class abst ract ...
abs t r ac t c l as s My I t er at or Wr apper i mpl ement s I t er at or
{

I nt er f ac e I t er at or {
f unc t i on __c ons t r uc t ( I t er at or $i t )
f unc t i on r ewi nd( ) ;
{
f unc t i on v al i d( ) ;
$t hi s - >i t = $i t ;
f unc t i on c ur r ent ( ) ;
}
f unc t i on __c al l ( $f unc , $ar gs)
f unc t i on k ey( ) ;
{
f unc t i on nex t ( ) ;
$c al l ee = ar r ay ( $t hi s - >i t , $f unc) ; }
i f ( ! i s _c al l abl e( $c al l ee) ) {
t hr ow new BadMet hodCal l Ex c ept i on( ) ;
}
r et ur n c al l _us er _f unc _ar r ay( $c al l ee, $ar gs) ;
}

}

Marcus Börger

Introduction to Object-oriented programming with PHP

71

I nt erfaces and __call
;
;

I nt erface funct ions cannot be handled by __call
...or provide t he funct ions ( here as proxy/ forward)
c l as s My I t er at or Wr apper i mpl ement s I t er at or
{
I nt er f ac e I t er at or {
f unc t i on __c ons t r uc t ( I t er at or $i t )
f unc t i on r ewi nd( ) ;
{
f unc t i on v al i d( ) ;
$t hi s - >i t = $i t ;
f unc t i on c ur r ent ( ) ;
}
f unc t i on __c al l ( $f unc , $ar gs)
f unc t i on k ey( ) ;
{
f unc t i on nex t ( ) ;
$c al l ee = ar r ay ( $t hi s - >i t , $f unc) ; }
i f ( ! i s _c al l abl e( $c al l ee) ) {
t hr ow new BadMet hodCal l Ex c ept i on( ) ;
}
r et ur n c al l _us er _f unc _ar r ay( $c al l ee, $ar gs) ;
}
f
f
f
f
f

unc t
unc t
unc t
unc t
unc t

i
i
i
i
i

on
on
on
on
on

r ewi nd( )
v al i d( )
c ur r ent ( )
k ey( )
nex t ( )

{
{
{
{
{

$t hi s - >i t
r et ur n $t
r et ur n $t
r et ur n $t
$t hi s - >i t

- >r ewi
hi s- >i
hi s- >i
hi s- >i
- >nex t

nd( ) ; }
t - >v al i d( ) ; }
t - >c ur r ent ( ) ; }
t - >k ey ( ) ; }
(); }

}
Marcus Börger

Introduction to Object-oriented programming with PHP

72

Expect ing form at t ed dat a
;

Opening a file for reading

Run-Time:

File might not be
accessible or exist
$f o = new Spl Fi l eObj ec t ( $f i l e) ;
$f o- >s et Fl ags ( Spl Fi l eObj ec t : : DROP_NEWLI NE) ;
$dat a = ar r ay ( ) ;

Marcus Börger

Introduction to Object-oriented programming with PHP

73

Expect ing form at t ed dat a
;

Reading a form at t ed file line by line

Run-Time:

File might not be
accessible or exist
$f o = new Spl Fi l eObj ec t ( $f i l e) ;
$f o- >s et Fl ags ( Spl Fi l eObj ec t : : DROP_NEWLI NE) ;
$dat a = ar r ay ( ) ;
f or eac h( $f o as $l ) {
i f ( / * * * CHECK DATA * * * / ) {
t hr ow new Except i on ( ) ;
Run-Time:
}
data is different for
$dat a[ ] = $l ;
every execution
}
;
;
;

! pr eg_mat c h( $r egex , $l )
c ount ( $l =s pl i t ( ' , ' , $l ) ) ! = 3
c ount ( $dat a) > 100

Marcus Börger

Unex pec t Val ueEx c ept i on
RangeEx c ept i on
Ov er f l owEx c ept i on

Introduction to Object-oriented programming with PHP

74

Expect ing form at t ed dat a
;

;
;
;

Cehcking dat a aft er pre- processing

Run-Time:

Filemight not be
accessible or exist
$f o = new Spl Fi l eObj ec t ( $f i l e) ;
$f o- >s et Fl ags ( Spl Fi l eObj ec t : : DROP_NEWLI NE) ;
$dat a = ar r ay ( ) ;
f or eac h( $f o as $l ) {
i f ( ! pr eg_mat c h( ' / \ d, \ d/ ' , $l ) ) {
t hr ow new Unex pec t edVal ueEx c ept i on( ) ; Run-Time:
}
data is different for
$dat a[ ] = $l ;
every execution
}
/ / Chec k s af t er t he f i l e was r ead ent i r el y
i f ( c ount ( $dat a) < 10) t hr ow new Under f l owEx c ept i on( ) ;
i f ( c ount ( $dat a) > 99) t hr ow new Ov er f l owEx c ept i on( ) ;
i f ( c ount ( $dat a) < 10 | | c ount ( $dat a) > 99)
t hr ow new Out Of Bounds Ex c ept i on( ) ;

Marcus Börger

Introduction to Object-oriented programming with PHP

75

Expect ing form at t ed dat a
;

Processing pre- checked dat a

Run-Time:

File might not be
accessible or exist
$f o = new Spl Fi l eObj ec t ( $f i l e) ;
$f o- >s et Fl ags ( Spl Fi l eObj ec t : : DROP_NEWLI NE) ;
$dat a = ar r ay ( ) ;
f or eac h( $f o as $l ) {
i f ( ! pr eg_mat c h( ' / \ d, \ d/ ' , $l ) ) {
t hr ow new Unex pec t edVal ueEx c ept i on( ) ; Run-Time:
}
data is different for
$dat a[ ] = $l ;
every execution
}
i f ( c ount ( $dat a) < 10) t hr ow new Under f l owEx c ept i on( ) ;
/ / may be mor e pr ec es s i ng c ode
f or eac h( $dat a as &$v ) {
Compile-Time:
i f ( c ount ( $v ) == 2) {
exception signals
t hr ow new Domai nEx c ept i on( ) ;
failed precondition
}
$v = $v [ 0] * $v [ 1] ;
}
Marcus Börger

Introduction to Object-oriented programming with PHP

76

Re fle ct ion

Marcus Börger

Introduction to Object-oriented programming with PHP

77

Reflect ion API
;

Can reflect nearly all aspect s of your PHP code
; Funct ions
; Classes, Met hods, Propert ies
; Ext ensions
c l as s Foo {
publ i c $pr op;
f unc t i on Func ( $name) {
ec ho " Hel l o $name" ;
}
}
Ref
Ref
Ref
Ref
Ref

l
l
l
l
l

ec t
ec t
ec t
ec t
ec t

i
i
i
i
i

onCl as s : :
onObj ec t :
onMet hod:
onPr oper t
onEx t ens i

Marcus Börger

ex por t ( ' Foo' ) ;
: ex por t ( new Foo) ;
: ex por t ( ' Foo' , ' f unc ' ) ;
y: : ex por t ( ' Foo' , ' pr op' ) ;
on: : ex por t ( ' s t andar d' ) ;

Introduction to Object-oriented programming with PHP

78

Dynam ic obj ect creat ion
;

Reflect ion allows dynam ic obj ect creat ion
c l as s Tes t {
f unc t i on __c ons t r uc t ( $x , $y = NULL) {
$t hi s- >x = $x ;
$t hi s- >y = $y ;
}
}
f unc t i on new_obj ec t _ar r ay( $c l s, $ar gs = NULL) {
r et ur n c al l _us er _f unc _ar r ay(
ar r ay ( new Ref l ec t i onCl as s( $c l s) , ' newI ns t anc e' ) ,
$ar gs) ;
}
new_obj ec t _ar r ay( ' s t dCl as s ' ) ;
new_obj ec t _ar r ay( ' Tes t ' , ar r ay ( 1) ) ;
new_obj ec t _ar r ay( ' Tes t ' , ar r ay ( 1, 2) ) ;
Marcus Börger

Introduction to Object-oriented programming with PHP

79

Bu ilt - in I n t e r fa ce s

Marcus Börger

Introduction to Object-oriented programming with PHP

80

Built - in I nt erfaces
;

PHP 5 cont ains built - in int erfaces t hat allow you t o
change t he way t he engine t reat s obj ect s.
; Ar r ay Ac c es s
; I t er at or
; I t er at or Aggr egat e

;

Built - in ext ension SPL provides m ore I nt erfaces
and Classes
; Ar r ay Obj ec t , Ar r ay I t er at or
; Fi l t er I t er at or
; Rec ur s i v eI t er at or
; Use CLI :
php - - r e SPL
php - - r c Ar r ay Ac c es s
Marcus Börger

Introduction to Object-oriented programming with PHP

81

ArrayAccess
;
;

Allows for creat ing obj ect s t hat can be
t ransparent ly accessed by array synt ax.
When com bined wit h t he it erat or int erface, it
allows for creat ing ‘arrays wit h special propert ies’.
i nt er f ac e Ar r ay Ac c es s {
/ / @r et ur n whet her $of f s et i s v al i d ( t r ue/ f al s e)
f unc t i on of f s et Ex i s t s( $of f s et ) ;
/ / @r et ur n t he v al ue as s oc i at ed wi t h $of f s et
f unc t i on of f s et Get ( $of f s et ) ;
/ / as s oc i at e $v al ue wi t h $of f s et ( s t or e t he dat a)
f unc t i on of f s et Set ( $of f s et , $v al ue) ;
/ / uns et t he dat a as s oc i at ed wi t h $of f s et
f unc t i on of f s et Uns et ( $of f s et ) ;
}
Marcus Börger

Introduction to Object-oriented programming with PHP

82

ArrayAccess
;

ArrayAccess does not allow references
( t he following is an error)
c l as s My Ar r ay ex t ends Ar r ay Ac c es s {
f unc t i on &of f s et Get ( $of f s et ) { / * . . .
f unc t i on of f s et Set ( $of f s et , &$v al ue)
f unc t i on of f s et Ex i s t s( $of f s et ) { / * .
f unc t i on of f s et Uns et ( $of f s et ) { / * . .
}

Marcus Börger

*/ }
{ / * . . . */ }
. . */ }
. */ }

Introduction to Object-oriented programming with PHP

83

ArrayAccess Exam ple
;
;

We want t o creat e variables which can be shared
bet ween processes.
We will set up int ercept ion so t hat access at t em pt s
on t he variable are act ually perform ed t hrough a
DBM file.

Marcus Börger

Introduction to Object-oriented programming with PHP

84

Binding Access t o a DBM

Marcus Börger

Introduction to Object-oriented programming with PHP

85

A Trivial Exam ple


Marcus Börger

Introduction to Object-oriented programming with PHP

86

I t erat ors
;
;

Norm al obj ect s behave like arrays when used wit h
t he foreach const ruct
Specialized I t erat or obj ect s can be it erat ed
different ly

Marcus Börger

Introduction to Object-oriented programming with PHP

87

What are I t erat ors
;

I t erat ors are a concept t o it erat e anyt hing t hat
cont ains ot her t hings.

;

I t erat ors allow t o encapsulat e algorit hm s

Marcus Börger

Introduction to Object-oriented programming with PHP

88

What are I t erat ors
;

I t erat ors are a concept t o it erat e anyt hing t hat
cont ains ot her t hings. Exam ples:
;
;
;
;
;
;
;

;

Values and Keys in an array
Text lines in a file
Files in a direct ory
XML Elem ent s or At t ribut es
Dat abase query result s
Dat es in a calendar range
Bit s in an im age

Ar r ay Obj ec t , Ar r ay I t er at or
Spl Fi l eObj ec t
[ Rec ur s i v e] Di r ec t or y I t er at or
ext : Sim pleXML, DOM
ext : PDO, SQLit e, MySQLi
PECL/ dat e ( ?)
?

I t erat ors allow t o encapsulat e algorit hm s

Marcus Börger

Introduction to Object-oriented programming with PHP

89

What are I t erat ors
;

I t erat ors are a concept t o it erat e anyt hing t hat
cont ains ot her t hings. Exam ples:
;
;
;
;
;
;
;

;

Values and Keys in an array
Text lines in a file
Files in a direct ory
XML Elem ent s or At t ribut es
Dat abase query result s
Dat es in a calendar range
Bit s in an im age

Ar r ay Obj ec t , Ar r ay I t er at or
Spl Fi l eObj ec t
[ Rec ur s i v e] Di r ec t or y I t er at or
ext : Sim pleXML, DOM
ext : PDO, SQLit e, MySQLi
PECL/ dat e ( ?)
?

I t erat ors allow t o encapsulat e algorit hm s
; Classes and I nt erfaces provided by SPL:
AppendI t er at or , Cac hi ngI t er at or , Li mi t I t er at or ,
Fi l t er I t er at or , Empt y I t er at or , I nf i ni t eI t er at or ,
NoRewi ndI t er at or , Out er I t er at or , Par ent I t er at or ,
Rec ur s i v eI t er at or , Rec ur s i v eI t er at or I t er at or ,
Seek abl eI t er at or , Spl Fi l eObj ec t , . . .
Marcus Börger

Introduction to Object-oriented programming with PHP

90

Array vs. I t erat or
;

An array in PHP
;
;
;
;
;

;

can be rewound:
is valid unless it 's key is NULL:
have current values:
have keys:
can be forwarded:

Som et hing t hat is t raversable
; m a y know how t o be rewound:

$ar = ar r ay( )
r es et ( $ar )
! i s _nul l ( k ey( $ar ) )
c ur r ent ( $ar )
k ey( $ar )
nex t ( $ar )
$i t = new I t er at or ;
$i t - >r ewi nd( )

( does not r et ur n t he el ement )

; should know if t here is a value:
; m a y have a current value:
; m a y have a key:

$i t - >v al i d( )
$i t - >c ur r ent ( )
$i t - >k ey( )

( may r et ur n NULL at any t i me)

; can forward t o it s next elem ent :
Marcus Börger

$i t - >nex t ( )

Introduction to Object-oriented programming with PHP

91

The big difference
;

Ar r a ys
; require m em ory for all elem ent s
; allow t o access any elem ent direct ly

;

I t e r a t or s
;
;
;
;

;

only know one elem ent at a t im e
only require m em ory for t he current elem ent
forward access only
Access done by m et hod calls

Con t a in e r s
; require m em ory for all elem ent s
; allow t o access any elem ent direct ly
; can creat e ext ernal I t erat ors or are int ernal I t erat ors
Marcus Börger

Introduction to Object-oriented programming with PHP

92

The basic concept s
;

I t erat ors can be int ernal or ext ernal
also referred t o as act ive or passive

;

An int ernal it erat or m odifies t he obj ect it self

;

An ext ernal it erat or point s t o anot her obj ect
wit hout m odifying it

;

PHP always uses ext ernal it erat ors at engine- level

;

I t erat ors m ay it erat e over ot her it erat ors

Marcus Börger

Introduction to Object-oriented programming with PHP

93

PHP I t erat ors
;
;
;
;
;

Anyt hing t hat can be it erat ed im plem ent s Tr av er s abl e
Obj ect s im plem ent ing Tr av er s abl e can be used in f or eac h
User classes cannot im plem ent Tr av er s abl e
I t er at or Aggr egat e is for obj ect s t hat use ext ernal it erat ors
I t er at or is for int ernal t raversal or ext ernal it erat ors
Traversable

Iterator
IteratorAggregate

+ getIterator () : Iterator

Marcus Börger

+
+
+
+
+

rewind ()
valid ()
current ()
key ()
next ()

:
:
:
:
:

void
boolean
mixed
mixed
void

Introduction to Object-oriented programming with PHP

94

I m plem ent ing I t erat ors
Traversable

Iterator
IteratorAggregate
+
+
+
+
+

+ getIterator () : Iterator

rewind ()
valid ()
current ()
key ()
next ()

:
:
:
:
:

void
boolean
mixed
mixed
void

IteratorImpl
AggregateImpl

+ getIterator () : Iterator

Marcus Börger

+
+
+
+
+







rewind ()
valid ()
current ()
key ()
next ()

Introduction to Object-oriented programming with PHP

:
:
:
:
:

void
boolean
mixed
mixed
void

95

How I t erat ors work
;
;

I t erat ors can be used m anually
I t erat ors can be used im plicit ly wit h for e a ch



Marcus Börger

Introduction to Object-oriented programming with PHP

96

How I t erat ors work
;
;

I nt ernal I t erat ors
User I t erat ors
< ?php
int erface I t erat or {
funct ion rewind( ) ;
funct ion valid( ) ;
funct ion current ( ) ;
funct ion key( ) ;
funct ion next ( ) ;
}
?>
< ?php
$it = get _resource( ) ;
for ( $it - > rewind( ) ; $it - > valid( ) ; $it - > next ( ) ) {
$value = $it - > current ( ) ; $key = $it - > key( ) ;
}
?>
Marcus Börger

Introduction to Object-oriented programming with PHP

97

How I t erat ors work
;
;

I nt ernal I t erat ors
User I t erat ors
< ?php
int erface I t erat or {
funct ion rewind( ) ;
funct ion valid( ) ;
funct ion current ( ) ;
funct ion key( ) ;
funct ion next ( ) ;
}
?>

Marcus Börger

< ?php
$it = get _resource( ) ;
foreach( $it as $key= > $val) {
/ / access dat a
}
?>

Introduction to Object-oriented programming with PHP

98

How I t erat ors work
;
;

I nt ernal I t erat ors
User I t erat ors
< ?php
int erface I t erat or {
funct ion rewind( ) ;
funct ion valid( ) ;
funct ion current ( ) ;
funct ion key( ) ;
funct ion next ( ) ;
}
?>

< ?php
class Filt erI t erat or im plem ent s I t erat or {
funct ion __const ruct ( I t erat or $input ) ...
funct ion rewind( ) ...
funct ion accept ( ) ...
funct ion valid( ) ...
funct ion current ( ) ...
funct ion key( ) ...
funct ion next ( ) ...
}
?>

< ?php
$it = get _resource( ) ;
foreach( new Filt er( $it , $filt er_param ) as $key= > $val) {
/ / access filt ered dat a only
}
?>
Marcus Börger

Introduction to Object-oriented programming with PHP

99

Debug Session


Marcus Börger



0 => 1
1 => 2
2 => 3

Introduction to Object-oriented programming with PHP

100

;
;
;

Aren’t I t erat ors Point less in
PHP?

Why not j ust use arrays:
f or eac h( $s ome_ar r ay as $i t em) { / * . . . * / }
Aren't we m aking life m ore difficult t han need be?
No! For sim ple aggregat ions t he above works fine
( t hough it ’s slow) , but not everyt hing is an array.
What about :
; Buffered result set s
; Lazy I nit ializat ion
; Direct ories
; Anyt hing not already an array

Marcus Börger

Introduction to Object-oriented programming with PHP

101

I t erat ors by exam ple
;

Using I t erat ors you can efficient ly grab all groups
from I NI files

;

The building blocks:
;
;
;
;
;

A class t hat handles I NI files
An abst ract filt er I t erat or
A filt er t hat filt ers group nam es from t he I NI file input
An I t erat or t o read all ent ries in t he I NI file
Anot her filt er t hat allow t o search for specific groups

Marcus Börger

Introduction to Object-oriented programming with PHP

102

I NI file abst ract ion
c l as s DbaReader i mpl ement s I t er at or {
pr ot ec t ed $db = NULL;
pr i v at e $k ey = f al s e, $v al = f al s e;

}

f unc t i on __c ons t r uc t ( $f i l e, $handl er ) {
i f ( ! $t hi s - >db = dba_open( $f i l e, ' r ' , $handl er ) )
t hr ow new Ex c ept i on( " Coul d not open f i l e $f i l e" ) ;
}
f unc t i on __des t r uc t ( ) {
dba_c l os e( $t hi s - >db) ;
}
pr i v at e f unc t i on f et c h_dat a( $k ey ) {
i f ( ( $t hi s - >k ey = $k ey ) ! == f al s e)
$t hi s - >v al = dba_f et c h( $t hi s - >