I ntroduction to Object-oriented program m ing w ith PHP
Marcus Börger
PHP Quebec conference 2 0 0 7
I ntroduction to Object-oriented program m ing w ith PHP Marcus - - PowerPoint PPT Presentation
I ntroduction to Object-oriented program m ing w ith PHP Marcus Brger PHP Quebec conference 2 0 0 7 Overview What is OOP? PHP and OOP Exceptions Iterators Reflection Patterns Marcus Brger Introduction
PHP Quebec conference 2 0 0 7
Marcus Börger Introduction to Object-oriented programming with PHP 2
Marcus Börger Introduction to Object-oriented programming with PHP 3
cl ass Usel ess ext ends Nonsense { abst r act f unct i on bl aBl a( ) ; }
Marcus Börger Introduction to Object-oriented programming with PHP 4
Of course not. It’s designed to make those things easier though.
Marcus Börger Introduction to Object-oriented programming with PHP 5
Marcus Börger Introduction to Object-oriented programming with PHP 6
Marcus Börger Introduction to Object-oriented programming with PHP 7
Marcus Börger Introduction to Object-oriented programming with PHP 8
For instance, if you press a key on your laptop keyboard you do not know what is happening in detail. For you it is the same as if you press the keyboard of an ATM. We say the interface is the same. If another person has the same laptop the internal details would be exactly the same.
Marcus Börger Introduction to Object-oriented programming with PHP 9
For instance, if you publish a text that is not really different from publishing a picture. Both are content types and you might want to encapsulate the details on how to do the actual publishing in a class. And once you have that you can easily have content that consists of both pictures and text and yet use the same operations for publishing. Then later you might publish tables using the same interface.
Marcus Börger Introduction to Object-oriented programming with PHP 10
cl ass Si m pl e { f unct i on __const r uct ( ) { / * . . . * / } f unct i on __dest r uct ( ) { / * . . . * / } }
Marcus Börger Introduction to Object-oriented programming with PHP 11
public anyone can access it protected
private
final no one can re-declare it abstract someone else will implement this Why have these in PHP? Because sometimes self-discipline isn’t enough.
Marcus Börger Introduction to Object-oriented programming with PHP 12
Extensibility Reusability Code Consolidation Abstraction Responsibility
Marcus Börger Introduction to Object-oriented programming with PHP 13
You often end up with code that looks like this: f unct i on f oo_t o_xm l ( $f oo) { / / gener i c st uf f / / f oo- speci f i c st uf f } f unct i on bar _t o_xm l ( $bar ) { / / gener i c st uf f / / bar speci f i c st uf f }
Marcus Börger Introduction to Object-oriented programming with PHP 14
f unct i on base_t o_xm l ( $dat a) { / * . . . * / } f unct i on f oo_t o_xm l ( $f oo) { base_t o_xm l ( $f oo) ; / / f oo speci f i c st uf f } f unct i on bar _t o_xm l ( $bar ) { base_t o_xm l ( $bar ) ; / / bar speci f i c st uf f }
Marcus Börger Introduction to Object-oriented programming with PHP 15
cl ass Bar ext ends Base { publ i c f unct i on t oXM L( ) { par ent : : t oXM L( ) ; / / bar speci f i c st uf f } } cl ass Base { publ i c f unct i on t oXM L( ) { / * . . . * / } } cl ass Foo ext ends Base { publ i c f unct i on t oXM L( ) { par ent : : t oXM L( ) ; / / f oo speci f i c st uf f } }
Marcus Börger Introduction to Object-oriented programming with PHP 16
Procedurally dislpaying all the entries might look like: f or each( $ent r i es as $ent r y) { swi t ch( $ent r y[ ’ t ype’ ] ) { case ' pr of essi onal ' : di spl ay_pr of essi onal _ent r y( $ent r y) ; br eak; case ' per sonal ' : di spl ay_per sonal _ent r y( $ent r y) ; br eak; } }
Marcus Börger Introduction to Object-oriented programming with PHP 17
f or each( $ent r i es as $ent r y) { $ent r y- >di spl ay( ) ; }
Marcus Börger Introduction to Object-oriented programming with PHP 18
f or each( $ent r i es as $ent r y) { echo $ent r y; }
Marcus Börger Introduction to Object-oriented programming with PHP 19
Use the other way round (call other methods from a single toXML() function in a polymorphic way) Use switch/ case (though this is not the OO way)
Marcus Börger Introduction to Object-oriented programming with PHP 20
cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on snor e( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } }
Marcus Börger Introduction to Object-oriented programming with PHP 21
cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on snor e( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } } cl ass W
en ext ends Hum ans { publ i c f unct i on gi veBi r t h( ) { / * . . . * / } }
Marcus Börger Introduction to Object-oriented programming with PHP 22
cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } } cl ass W
en ext ends Hum ans { publ i c f unct i on gi veBi r t h( ) { / * . . . * / } } cl ass M en ext ends Hum ans { publ i c f unct i on snor e( ) { / * . . . * / } }
Marcus Börger Introduction to Object-oriented programming with PHP 23
abst r act cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } abst r act publ i c f unct i on gender ( ) ; publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } } cl ass W
en ext ends Hum ans { publ i c f unct i on gender ( ) { r et ur n ' f em al e' ; } publ i c f unct i on gi veBi r t h( ) { / * . . . * / } } cl ass M en ext ends Hum ans { publ i c f unct i on gender ( ) { r et ur n ' m al e' ; } publ i c f unct i on snor e( ) { / * . . . * / } }
Marcus Börger Introduction to Object-oriented programming with PHP 24
abst r act cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } abst r act publ i c f unct i on gender ( ) ; publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } } cl ass W
en ext ends Hum ans { f i nal publ i c f unct i on gender ( ) { r et ur n ' f ' ; } publ i c f unct i on gi veBi r t h( ) { / * . . . * / } } cl ass M en ext ends Hum ans { f i nal publ i c f unct i on gender ( ) { r et ur n ' m ' ; } publ i c f unct i on snor e( ) { / * . . . * / } }
Marcus Börger Introduction to Object-oriented programming with PHP 25
Marcus Börger Introduction to Object-oriented programming with PHP 26
Methods
No visibility No abstracts, no final Static without declaration
Properties
No static properties No constants
Inheritance
No abstract, final inheritance, no interfaces No prototype checking, no types
Object handling
Copied by value No destructors
Marcus Börger Introduction to Object-oriented programming with PHP 27
Marcus Börger Introduction to Object-oriented programming with PHP 28
Better code reuse Better for team development Easier to refactor Some patterns lead to much more efficient code Fits better in marketing scenarios
Marcus Börger Introduction to Object-oriented programming with PHP 29
Marcus Börger Introduction to Object-oriented programming with PHP 30
cl ass O bj ect { } ; $obj = new O bj ect ( ) ; $r ef = $obj ; $dup = cl one cl one $obj ; Class Object $obj $ref $dup Instance 1 Instance 2
Marcus Börger Introduction to Object-oriented programming with PHP 31
Constructors may have both new OR old style name
New style constructors are preferred Constructors must not use inherited protocol
Destructors are called when deleting the last reference
No particular or controllable order during shutdown Destructors cannot have parameters Since PHP 5.0.1 destructors can work with resources cl ass O bj ect { f unct i on __const r uct __const r uct ( ) { } f unct i on __dest r uct __dest r uct ( ) { } } $obj = new O bj ect ( ) ; unset ( $obj ) ;
Marcus Börger Introduction to Object-oriented programming with PHP 32
cl ass Base { f unct i on __const r uct ( ) { } f unct i on __dest r uct ( ) { } } cl ass O bj ect ext ends Base { f unct i on __const r uct ( ) { par ent par ent : : __const r uct ( ) ; } f unct i on __dest r uct ( ) { par ent par ent : : __dest r uct ( ) ; } } $obj = new O bj ect ( ) ; unset ( $obj ) ;
Marcus Börger Introduction to Object-oriented programming with PHP 33
Bound to the class not to the object Default values cannot be changed but overwritten cl ass O bj ect { var $pr op = " Hel l o\ n" ; } $obj 1 = new O bj ect ; $obj 1- >pr op = " Hel l o W
$obj 2 = new O bj ect ; echo $obj 2- >pr op; / / Hel l o
Class Object $prop/default $obj2 Instance 2 $prop $obj1 Instance 1 $prop
Marcus Börger Introduction to Object-oriented programming with PHP 34
Bound to the class not to the object
Only exists once per class rather than per instance
Can be initialized cl ass O bj ect { var $pr op; st at i c st at i c $st at = " Hel l o\ n" ; st at i c st at i c f unct i on t est ( ) { echo sel f sel f : : $st at ; } } O bj ect : : t est ( ) ; $obj 1 = new O bj ect ; $obj 2 = new O bj ect ;
Class Object $stat $obj2 Instance 2 $prop $obj1 Instance 1 $prop
Marcus Börger Introduction to Object-oriented programming with PHP 35
__CLASS__ shows the current class name
ETHO D__ __M ETHO D__ shows class and method or function
sel f references the class itself
par ent references the parent class
$t hi s references the object itself
cl ass Base { st at i c f unct i on Show( ) { echo __FI LE__. ' ( ' . __LI NE__. ' ) : ' . __M ETHO D__. " \ n" ; } } cl ass O bj ect ext ends Base { st at i c f unct i on Use( ) { Sel f : : Show( ) ; Par ent : : Show( ) ; } st at i c f unct i on Show( ) { echo __FI LE__. ' ( ' . __LI NE__. ' ) : ' . __M ETHO D__. " \ n" ; } }
Marcus Börger Introduction to Object-oriented programming with PHP 36
A derived class doesn't know parents private members An inherited protected member can be made public
cl ass Base { publ i c publ i c $a; pr ot ect ed pr ot ect ed $b; pr i vat e pr i vat e $c; } cl ass Der i ved ext ends Base { publ i c publ i c $a; publ i c publ i c $b; pr i vat e pr i vat e $c; } Base $a $b $c Derived $a $b $c Base::$c
Marcus Börger Introduction to Object-oriented programming with PHP 37
cl ass Base { pr ot ect ed f unct i on __const r uct ( ) { } } cl ass Der i ved ext ends Base { / / const r uct or i s st i l l pr ot ect ed st at i c f unct i on get Base( ) { r et ur n new Base; / / Fact or y pat t er n } } cl ass Thr ee ext ends Der i ved { publ i c f unct i on __const r uct ( ) { } }
Marcus Börger Introduction to Object-oriented programming with PHP 38
DB connections An object representing the user or connection.
cl ass Si ngl et on { st at i c pr i vat e $i nst ance; pr ot ect ed f unct i on __const r uct ( ) { } f i nal pr i vat e f unct i on __cl one( ) { } st at i c f unct i on get I nst ance( ) { i f ( ! sel f : : $i nst ance) sel f : : $i nst ance = new Si ngl et on( ) ; r et ur n sel f : : $i nst ance; } } $a = Si ngl et on: : get I nst ance( ) ; $a- >i d = 1; $b = Si ngl et on: : get I nst ance( ) ; pr i nt $b- >i d. " \ n" ;
Marcus Börger Introduction to Object-oriented programming with PHP 39
cl ass Base { const const gr eet i ng = " Hel l o\ n" ; } cl ass Der vi ed ext ends Base { const const gr eet i ng = " Hel l o W
st at i c f unct i on f unc( ) { echo par ent : : gr eet i ng; } } echo Base: : gr eet i ng; echo Der i ved: : gr eet i ng; Der i ved: : f unc( ) ;
Marcus Börger Introduction to Object-oriented programming with PHP 40
They don’t have a body A class with an abstract method must be abstract
The class cannot be instantiated
abst r act abst r act cl ass Base { abst r act abst r act f unct i on no_body( ) ; } cl ass Der i ved ext ends Base { f unct i on no_body( ) { echo " Body\ n" ; } }
Marcus Börger Introduction to Object-oriented programming with PHP 41
They cannot be overwritten They are class invariants
They cannot be inherited
cl ass Base { f i nal f i nal f unct i on i nvar i ant ( ) { echo " Hel l o\ n" ; } } cl ass Der i ved ext ends Base { } f i nal f i nal cl ass Leaf ext ends Der i ved { }
Marcus Börger Introduction to Object-oriented programming with PHP 42
cl ass Li ne { f unct i on dr aw( ) { } ; } cl ass 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( ) ; } } cl ass Rect angl e ext ends Pol ygon { } cl ass El l i pse { f unct i on dr aw( ) { } ; } cl ass Ci r cl e ext ends El l i pse { f unct i on dr aw( ) { par ent : : dr aw( ) ; } }
Polygon Line Ellipse Circle $lines Rectangle
Marcus Börger Introduction to Object-oriented programming with PHP 43
i nt er f ace Dr awabl e { f unct i on dr aw( ) ; } cl ass Li ne i m pl em ent s Dr awabl e { f unct i on dr aw( ) { } ; } cl ass Pol ygon i m pl em ent 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( ) ; } } cl ass Rect angl e ext ends Pol ygon { } cl ass El l i pse i m pl em ent s Dr awabl e { f unct i on dr aw( ) { } ; } cl ass Ci r cl e ext ends El l i pse { f unct i on dr aw( ) { par ent : : dr aw( ) ; } }
Drawable Polygon Line Ellipse Circle $lines Rectangle
Marcus Börger Introduction to Object-oriented programming with PHP 44
May have a default value Can have selected visibility
Declared by simply using them in ANY method
Handled by interceptor methods
Bound to the class rather than to the instance
Marcus Börger Introduction to Object-oriented programming with PHP 45
cl ass O bj ect { f unct i on __t oSt r i ng __t oSt r i ng( ) { r et ur n ' O bj ect as st r i ng' ; } } $o = new O bj ect ; echo $o; / / does cal l __t oSt r i ng $st r = ( st r i ng) $o; / / does cal l __t oSt r i ng
Marcus Börger Introduction to Object-oriented programming with PHP 46
Lazy initialization of properties Simulating Object aggregation and Multiple inheritance
cl ass O bj ect { pr ot ect ed $vi r t ual = ar r ay( ) ; f unct i on __get __get ( $nam e) { r et ur n @ $t hi s- >vi r t ual [ $nam e] ; } f unct i on __set __set ( $nam e, $val ue) { $t hi s- >vi r t ual [ $nam e] = $val ue; } f unct i on __unset __unset ( $nam e) { unset ( $t hi s- >vi r t ual [ $nam e] ) ; } f unct i on __i sset __i sset ( $nam e) { r et ur n i sset ( $t hi s- >vi r t ual [ $nam e] ) ; } f unct i on __cal l __cal l ( $f unc, $par am s) { echo ' Coul d not cal l ' . __CLASS__ . ' : : ' . $f unc . " \ n" ; } }
Marcus Börger Introduction to Object-oriented programming with PHP 47
PHP does not allow NULL for typehints Typehints must be inherited as given in base class PHP 5.1 offers typehinting with arrays PHP 5.2 offers optional typehinted parameters (= NULL)
cl ass O bj ect { publ i c f unct i on com par e( O bj ect $ot her ) { / / Som e code her e } publ i c f unct i on com par e2( $ot her ) { i f ( i s_nul l ( $ot her ) | | $ot her i nst anceof O bj ect ) { / / Som e code her e } } }
Marcus Börger Introduction to Object-oriented programming with PHP 48
Vehicle Truck Car Bus Diesel Gasoline Engine Bicycle Tires Turbine Tank Plane
Marcus Börger Introduction to Object-oriented programming with PHP 49
You are bound to keep inherited signatures You cannot change from ref to non-ref return
Just do not define a signature Warning: This is extremely error prone
Marcus Börger Introduction to Object-oriented programming with PHP 50
Marcus Börger Introduction to Object-oriented programming with PHP 51
Requires a single file for each class Only load class files when necessary
No need to parse/ compile unneeded classes No need to check which class files to load
Additional user space code Only one single loader model is possible
Marcus Börger Introduction to Object-oriented programming with PHP 52
I n each scr i pt : r equi r e_once( ' <pat h>/ aut ol oad. i nc' ) Use I NI opt i on: aut o_pr epend_f i l e=<pat h>/ aut ol oad. i nc
<?php f unct i on __aut ol oad( $cl ass_nam e) { r equi r e_once( di r nam e( __FI LE__) . ' / ' . $cl ass_nam e . ' . p5c' ) ; } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 53
Look into path's specified by INI option include_path Look for specified file extensions (.inc, .php)
You need to register __autoload if using spl's autoload
<?php spl _aut ol oad_r egi st er ( ' spl _aut ol oad' ) ; i f ( f unct i on_exi st s( ' __aut ol oad' ) ) { spl _aut ol oad_r egi st er ( ' __aut ol oad' ) ; } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 54
Marcus Börger Introduction to Object-oriented programming with PHP 55
Marcus Börger Introduction to Object-oriented programming with PHP 56
<?php t r y t r y { / / your code t hr ow t hr ow new Except i on( ) ; } cat ch cat ch ( Except i on $e) { / / except i on handl i ng } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 57
cl ass Your Except i on ext ends Except i on { } t r y { / / your code t hr ow new Your Except i on( ) ; } cat ch ( Your Except i on $e) { / / except i on handl i ng } cat ch ( Except i on $e) { / / except i on handl i ng }
Marcus Börger Introduction to Object-oriented programming with PHP 58
cl ass Your Except i on ext ends Except i on { } t r y { t r y { / / your code t hr ow new Your Except i on( ) ; } cat ch ( Your Except i on $e) { / / except i on handl i ng t hr ow $e; } cat ch ( Except i on $e) { / / except i on handl i ng } } cat ch ( Your Except i on $e) { / / except i on handl i ng }
Marcus Börger Introduction to Object-oriented programming with PHP 59
Marcus Börger Introduction to Object-oriented programming with PHP 60
<?php cl ass O bj ect { f unct i on __const r uct ( & $f ai l ur e) / / " O bj ect " i n PHP 4 { $f ai l ur e = t r ue; } } $er r or = f al se; $o = new O bj ect ( $er r or ) ; i f ( ! $er r or ) { / / er r or handl i ng, NO TE: t he obj ect was const r uct ed unset ( $o) ; } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 61
<?php cl ass O bj ect { f unct i on __const r uct ( ) { t hr ow new Except i on; } } t r y { $o = new O bj ect ; } cat ch ( Except i on $e) { echo " O bj ect coul d not be i nst ant i at ed\ n" ; } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 62
<?php i f ( ! cl ass_exi st s( ' Er r or Except i on' , f al se) ) { cl ass Er r or Except i on ext ends Except i on { pr ot ect ed $sever i t y; f unct i on __const r uct ( $m sg, $code, $er r no, $f i l e, $l i ne) { par ent : : __const r uct ( $m sg, $code) ; $t hi s- >sever i t y = $er r no; $t hi s- >f i l e = $f i l e; $t hi s- >l i ne = $l i ne; } f unct i on get Sever i t y( ) { r et ur n $t hi s- >sever i t y; } } } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 63
<?php f unct i on Er r or sToExcept i ons( $er r no, $m sg, $f i l e, $l i ne) { t hr ow new Er r or Except i on( $m sg, 0, $er r no, $f i l e, $l i ne) ; } set _er r or _handl er ( ' Er r or sToExcept i ons' ) ; ?>
Marcus Börger Introduction to Object-oriented programming with PHP 64
<ht m l ><body> <?php $ok = f al se; $db = new PDO ( ' CO NNECTI O N' ) ; i f ( $db) { $r es = $db- >quer y( ' SELECT dat a' ) ; i f ( $r es) { $r es2 = $db- >quer y( ' SELECT ot her ' ) ; i f ( $r es2) { / / handl e dat a $ok = t r ue; / / onl y i f al l went ok } } } i f ( ! $ok) echo ' <h1>Ser vi ce cur r ent l y unavai l abl e</ h1>' ; ?> </ body></ ht m l >
Marcus Börger Introduction to Object-oriented programming with PHP 65
<ht m l ><body> <?php t r y { $db = new PDO ( ' CO NNECTI O N' ) ; $db- >set At t r i but e( PDO : : ATTR_ERRM O DE, PDO : : ERRM O DE_EXCEPTI O N) ; $r es = $db- >quer y( ' SELECT dat a' ) ; $r es2 = $db- >quer y( ' SELECT ot her ' ) ; / / handl e dat a } cat ch ( Except i on $e) { echo ' <h1>Ser vi ce cur r ent l y unavai l abl e</ h1>' ; er r or _l og( $e- >get M essage( ) ) ; } ?> </ body></ ht m l >
Marcus Börger Introduction to Object-oriented programming with PHP 66
Marcus Börger Introduction to Object-oriented programming with PHP 67
Marcus Börger Introduction to Object-oriented programming with PHP 68
BadM et hodCal l Except i on
Marcus Börger Introduction to Object-oriented programming with PHP 69
Marcus Börger Introduction to Object-oriented programming with PHP 70
abst r act cl ass M yI t er at or W r apper i m pl em ent s I t er at or { f unct i on __const r uct ( I t er at or $i t ) { $t hi s- >i t = $i t ; } f unct i on __cal l ( $f unc, $ar gs) { $cal l ee = ar r ay( $t hi s- >i t , $f unc) ; i f ( ! i s_cal l abl e( $cal l ee) ) { t hr ow new BadM et hodCal l Except i on( ) ; } r et ur n cal l _user _f unc_ar r ay( $cal l ee, $ar gs) ; } }
Compile-Time: Error in design
Marcus Börger Introduction to Object-oriented programming with PHP 71
abst r act
cl ass M yI t er at or W r apper i m pl em ent s I t er at or { f unct i on __const r uct ( I t er at or $i t ) { $t hi s- >i t = $i t ; } f unct i on __cal l ( $f unc, $ar gs) { $cal l ee = ar r ay( $t hi s- >i t , $f unc) ; i f ( ! i s_cal l abl e( $cal l ee) ) { t hr ow new BadM et hodCal l Except i on( ) ; } r et ur n cal l _user _f unc_ar r ay( $cal l ee, $ar gs) ; } } } I nt er f ace I t er at or { f unct i on r ewi nd( ) ; f unct i on val i d( ) ; f unct i on cur r ent ( ) ; f unct i on key( ) ; f unct i on next ( ) ;
Marcus Börger Introduction to Object-oriented programming with PHP 72
cl ass M yI t er at or W r apper i m pl em ent s I t er at or { f unct i on __const r uct ( I t er at or $i t ) { $t hi s- >i t = $i t ; } f unct i on __cal l ( $f unc, $ar gs) { $cal l ee = ar r ay( $t hi s- >i t , $f unc) ; i f ( ! i s_cal l abl e( $cal l ee) ) { t hr ow new BadM et hodCal l Except i on( ) ; } r et ur n cal l _user _f unc_ar r ay( $cal l ee, $ar gs) ; } f unct i on r ewi nd( ) { $t hi s- >i t - >r ewi nd( ) ; } f unct i on val i d( ) { r et ur n $t hi s- >i t - >val i d( ) ; } f unct i on cur r ent ( ) { r et ur n $t hi s- >i t - >cur r ent ( ) ; } f unct i on key( ) { r et ur n $t hi s- >i t - >key( ) ; } f unct i on next ( ) { $t hi s- >i t - >next ( ) ; } } } I nt er f ace I t er at or { f unct i on r ewi nd( ) ; f unct i on val i d( ) ; f unct i on cur r ent ( ) ; f unct i on key( ) ; f unct i on next ( ) ;
Marcus Börger Introduction to Object-oriented programming with PHP 73
$f o = new Spl Fi l eO bj ect ( $f i l e) ; $f o- >set Fl ags( Spl Fi l eO bj ect : : DRO P_NEW LI NE) ; $dat a = ar r ay( ) ; Run-Time: File might not be accessible or exist
Marcus Börger Introduction to Object-oriented programming with PHP 74
$f o = new Spl Fi l eO bj ect ( $f i l e) ; $f o- >set Fl ags( Spl Fi l eO bj ect : : DRO P_NEW LI NE) ; $dat a = ar r ay( ) ; f or each( $f o as $l ) { i f ( / * * * CHECK DATA * * * / ) { t hr ow new Except i on( ) ; } $dat a[ ] = $l ; }
at ch( $r egex, $l ) Unexpect Val ueExcept i on
$l ) ) ! = 3 RangeExcept i on
O ver f l owExcept i on Run-Time: File might not be accessible or exist Run-Time: data is different for every execution
Marcus Börger Introduction to Object-oriented programming with PHP 75
$f o = new Spl Fi l eO bj ect ( $f i l e) ; $f o- >set Fl ags( Spl Fi l eO bj ect : : DRO P_NEW LI NE) ; $dat a = ar r ay( ) ; f or each( $f o as $l ) { i f ( ! pr eg_m at ch( ' / \ d, \ d/ ' , $l ) ) { t hr ow new Unexpect edVal ueExcept i on( ) ; } $dat a[ ] = $l ; } / / Checks af t er t he f i l e was r ead ent i r el y
t hr ow new Under f l owExcept i on( ) ;
t hr ow new O ver f l owExcept i on( ) ;
t hr ow new O ut O f BoundsExcept i on( ) ; Run-Time: data is different for every execution Run-Time: Filemight not be accessible or exist
Marcus Börger Introduction to Object-oriented programming with PHP 76
$f o = new Spl Fi l eO bj ect ( $f i l e) ; $f o- >set Fl ags( Spl Fi l eO bj ect : : DRO P_NEW LI NE) ; $dat a = ar r ay( ) ; f or each( $f o as $l ) { i f ( ! pr eg_m at ch( ' / \ d, \ d/ ' , $l ) ) { t hr ow new Unexpect edVal ueExcept i on( ) ; } $dat a[ ] = $l ; } i f ( count ( $dat a) < 10) t hr ow new Under f l owExcept i on( ) ; / / m aybe m
f or each( $dat a as &$v) { i f ( count ( $v) == 2) { t hr ow new Dom ai nExcept i on( ) ; } $v = $v[ 0] * $v[ 1] ; } Compile-Time: exception signals failed precondition Run-Time: data is different for every execution Run-Time: File might not be accessible or exist
Marcus Börger Introduction to Object-oriented programming with PHP 77
Marcus Börger Introduction to Object-oriented programming with PHP 78
Functions Classes, Methods, Properties Extensions
cl ass Foo { publ i c $pr op; f unct i on Func( $nam e) { echo " Hel l o $nam e" ; } } Ref l ect i onCl ass: : expor t ( ' Foo' ) ; Ref l ect i onO bj ect : : expor t ( new Foo) ; Ref l ect i onM et hod: : expor t ( ' Foo' , ' f unc' ) ; Ref l ect i onPr oper t y: : expor t ( ' Foo' , ' pr op' ) ; Ref l ect i onExt ensi on: : expor t ( ' st andar d' ) ;
Marcus Börger Introduction to Object-oriented programming with PHP 79
cl ass Test { f unct i on __const r uct ( $x, $y = NULL) { $t hi s- >x = $x; $t hi s- >y = $y; } } f unct i on new_obj ect _ar r ay( $cl s, $ar gs = NULL) { r et ur n cal l _user _f unc_ar r ay( ar r ay( new Ref l ect i onCl ass( $cl s) , ' newI nst ance' ) , $ar gs) ; } new_obj ect _ar r ay( ' st dCl ass' ) ; new_obj ect _ar r ay( ' Test ' , ar r ay( 1) ) ; new_obj ect _ar r ay( ' Test ' , ar r ay( 1, 2) ) ;
Marcus Börger Introduction to Object-oriented programming with PHP 80
Marcus Börger Introduction to Object-oriented programming with PHP 81
Ar r ayAccess I t er at or I t er at or Aggr egat e
Ar r ayO bj ect , Ar r ayI t er at or Fi l t er I t er at or Recur si veI t er at or Use CLI: php - - r e SPL php - - r c Ar r ayAccess
Marcus Börger Introduction to Object-oriented programming with PHP 82
i nt er f ace Ar r ayAccess { / / @ r et ur n whet her $of f set i s val i d ( t r ue/ f al se) f unct i on of f set Exi st s( $of f set ) ; / / @ r et ur n t he val ue associ at ed wi t h $of f set f unct i on of f set G et ( $of f set ) ; / / associ at e $val ue wi t h $of f set ( st or e t he dat a) f unct i on of f set Set ( $of f set , $val ue) ; / / unset t he dat a associ at ed wi t h $of f set f unct i on of f set Unset ( $of f set ) ; }
Marcus Börger Introduction to Object-oriented programming with PHP 83
cl ass M yAr r ay ext ends Ar r ayAccess { f unct i on &of f set G et ( $of f set ) { / * . . . * / } f unct i on of f set Set ( $of f set , &$val ue) { / * . . . * / } f unct i on of f set Exi st s( $of f set ) { / * . . . * / } f unct i on of f set Unset ( $of f set ) { / * . . . * / } }
Marcus Börger Introduction to Object-oriented programming with PHP 84
Marcus Börger Introduction to Object-oriented programming with PHP 85
<?php cl ass DbaReader i m pl em ent s Ar r ayAccess { pr ot ect ed $db = NULL; f unct i on __const r uct ( $f i l e, $handl er ) { i f ( ! $t hi s- >db = dba_open( $f i l e, ' cd' , $handl er ) ) t hr ow new except i on( ' Coul d not open f i l e ' . $f i l e) ; } f unct i on __dest r uct ( ) { dba_cl ose( $t hi s- >db) ; } f unct i on of f set Exi st s( $of f set ) { r et ur n dba_exi st s( $of f set , $t hi s- >db) ; } f unct i on of f set G et ( $of f set ) { r et ur n dba_f et ch( $of f set , $t hi s- >db) ; } f unct i on of f set Set ( $of f set , $val ue) { r et ur n dba_r epl ace( $of f set , $val ue, $t hi s- >db) ; } f unct i on of f set Unset ( $of f set ) { r et ur n dba_del et e( $of f set , $t hi s- >db) ; } } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 86
<?php i f ( ! cl ass_exi st s( ' DbaReader ' , f al se) ) { r equi r e_once ‘ dbadeader . i nc’ ; } $_SHARED = new DbaReader ( ' / t m p/ . count er ' , ' f l at f i l e' ) ; $_SHARED[ ' count er ' ] += 1; pr i nt f ( " PI D: % d\ nCO UNTER: % d\ n" , get m ypi d( ) , $_SHARED[ ' count er ' ] ) ; ?>
Marcus Börger Introduction to Object-oriented programming with PHP 87
<?php cl ass O bj ect { publ i c $pr op1 = " Hel l o " ; publ i c $pr op2 = " W
} f or each( new O bj ect as $pr op) { echo $pr op; } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 88
Marcus Börger Introduction to Object-oriented programming with PHP 89
Values and Keys in an array Ar r ayO bj ect , Ar r ayI t er at or Text lines in a file Spl Fi l eO bj ect Files in a directory [ Recur si ve] Di r ect or yI t er at or XML Elements or Attributes ext: SimpleXML, DOM Database query results ext: PDO, SQLite, MySQLi Dates in a calendar range PECL/ date (?) Bits in an image ?
Marcus Börger Introduction to Object-oriented programming with PHP 90
Values and Keys in an array Ar r ayO bj ect , Ar r ayI t er at or Text lines in a file Spl Fi l eO bj ect Files in a directory [ Recur si ve] Di r ect or yI t er at or XML Elements or Attributes ext: SimpleXML, DOM Database query results ext: PDO, SQLite, MySQLi Dates in a calendar range PECL/ date (?) Bits in an image ?
Classes and Interfaces provided by SPL:
AppendI t er at or , Cachi ngI t er at or , Li m i t I t er at or , Fi l t er I t er at or , Em pt yI t er at or , I nf i ni t eI t er at or , NoRewi ndI t er at or , O ut er I t er at or , Par ent I t er at or , Recur si veI t er at or , Recur si veI t er at or I t er at or , Seekabl eI t er at or , Spl Fi l eO bj ect , . . .
Marcus Börger Introduction to Object-oriented programming with PHP 91
$ar = ar r ay( ) can be rewound: r eset ( $ar ) is valid unless it's key is NULL: ! i s_nul l ( key( $ar ) ) have current values: cur r ent ( $ar ) have keys: key( $ar ) can be forwarded: next ( $ar )
$i t = new I t er at or ; m ay know how to be rewound: $i t - >r ewi nd( )
( does not r et ur n t he el em ent )
should know if there is a value: $i t - >val i d( ) m ay have a current value: $i t - >cur r ent ( ) m ay have a key: $i t - >key( )
( m ay r et ur n NULL at any t i m e)
can forward to its next element: $i t - >next ()
Marcus Börger Introduction to Object-oriented programming with PHP 92
require memory for all elements allow to access any element directly
forward access only Access done by method calls
require memory for all elements allow to access any element directly can create external Iterators or are internal Iterators
Marcus Börger Introduction to Object-oriented programming with PHP 93
Marcus Börger Introduction to Object-oriented programming with PHP 94
Tr aver sabl e
Tr aver sabl e can be used in f or each f or each
Tr aver sabl e
I t er at or Aggr egat e is for objects that use external iterators
I t er at or is for internal traversal or external iterators
IteratorAggregate + getIterator () : Iterator Traversable Iterator + + + + + rewind () valid () current () key () next () : void : boolean : mixed : mixed : void
Marcus Börger Introduction to Object-oriented programming with PHP 95
Traversable IteratorAggregate + getIterator () : Iterator Iterator + + + + + rewind () valid () current () key () next () : void : boolean : mixed : mixed : void AggregateImpl + <<Implement>> getIterator () : Iterator IteratorImpl + + + + + <<Implement>> <<Implement>> <<Implement>> <<Implement>> <<Implement>> rewind () valid () current () key () next () : void : boolean : mixed : mixed : void
Marcus Börger Introduction to Object-oriented programming with PHP 96
<?php $o = new Ar r ayI t er at or ( ar r ay( 1, 2, 3) ) ; $o- >r ewi nd( ) ; whi l e ( $o- >val i d( ) ) { $key = $o- >key( ) ; $val = $o- >cur r ent ( ) ; / / som e code $o- >next ( ) ; } ?> <?php $o = new Ar r ayI t er at or ( ar r ay( 1, 2, 3) ) ; f or each( $o as $key => $val ) { / / som e code } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 97
< ?php $it = get_resource(); for ($it-> rewind(); $it-> valid(); $it-> next()) { $value = $it-> current(); $key = $it-> key(); } ?>
< ?php interface Iterator { function rewind(); function valid(); function current(); function key(); function next(); } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 98
< ?php $it = get_resource(); foreach($it as $key= > $val) { / / access data } ?> < ?php interface Iterator { function rewind(); function valid(); function current(); function key(); function next(); } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 99
< ?php $it = get_resource(); foreach(new Filter($it, $filter_param) as $key= > $val) { / / access filtered data only } ?> < ?php class FilterIterator implements Iterator { function __construct(Iterator $input)... function rewind()... function accept()... function valid()... function current()... function key()... function next()... } ?>
< ?php interface Iterator { function rewind(); function valid(); function current(); function key(); function next(); } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 100
<?php cl ass Ar r ayI t er at or { pr ot ect ed $ar ; f unct i on __const r uct ( Ar r ay $ar ) { $t hi s- >ar = $ar ; } f unct i on r ewi nd( ) { r ewi nd( $t hi s- >ar ) ; } f ucnt i on val i d( ) { r et ur n ! i s_nul l ( key( $t hi s- >ar ) ) ; } f unct i on key( ) { r et ur n key( $t hi s- >ar ) ; } f ucnt i on cur r ent ( ) { r et ur n cur r ent ( $t hi s- >ar ) ; } f unct i on next ( ) { next ( $t hi s- >ar ) ; } } ?> <?php $a = ar r ay( 1, 2, 3) ; $o = new Ar r ayI t er at or ( $a) ; f or each( $o as $key => $val ) { echo " $key => $va\ n" ; } ?> 0 => 1 1 => 2 2 => 3
PHP 5.1
Marcus Börger Introduction to Object-oriented programming with PHP 101
Buffered result sets Lazy Initialization Directories Anything not already an array
Marcus Börger Introduction to Object-oriented programming with PHP 102
A class that handles INI files An abstract filter Iterator A filter that filters group names from the INI file input An Iterator to read all entries in the INI file Another filter that allow to search for specific groups
Marcus Börger Introduction to Object-oriented programming with PHP 103
cl ass DbaReader i m pl em ent s I t er at or { pr ot ect ed $db = NULL; pr i vat e $key = f al se, $val = f al se; f unct i on __const r uct ( $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 Except i on( " Coul d not open f i l e $f i l e" ) ; } f unct i on __dest r uct ( ) { dba_cl ose( $t hi s- >db) ; } pr i vat e f unct i on f et ch_dat a( $key) { i f ( ( $t hi s- >key = $key) ! == f al se) $t hi s- >val = dba_f et ch( $t hi s- >key, $t hi s- >db) ; } f unct i on r ewi nd( ) { $t hi s- >f et ch_dat a( dba_f i r st key( $t hi s- >db) ) ; } f unct i on next ( ) { $t hi s- >f et ch_dat a( dba_next key( $t hi s- >db) ) ; } f unct i on cur r ent ( ) { r et ur n $t hi s- >val ; } f unct i on val i d( ) { r et ur n $t hi s- >key ! == f al se; } f unct i on key( ) { r et ur n $t hi s- >key; } }
Marcus Börger Introduction to Object-oriented programming with PHP 104
Abstract accept() is called from rewind() and next()
When accept() returns false next() will be called automatically
<?php cl ass KeyFi l t er ext ends Fi l t er I t er at or { pr i vat e $r x; f unct i on __const r uct ( I t er at or $i t , $r egex) { par ent : : __const r uct ( $i t ) ; $t hi s- >r x = $r egex; } f unct i on accept ( ) { r et ur n er eg( $t hi s- >r x, $t hi s- >get I nner I t er at or ( ) - >key( ) ) ; } f unct i on get Regex( ) { r et ur n $t hi s- >r x; } pr ot ect ed f unct i on __cl one( $t hat ) { / / di sal l ow cl one } } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 105
<?php i f ( ! cl ass_exi st s( ' KeyFi l t er ' , f al se) ) { r equi r e_once( ' keyf i l t er . i nc' ) ; } cl ass I ni G r oups ext ends KeyFi l t er { f unct i on __const r uct ( $f i l e) { par ent : : __const r uct ( new DbaReader ( $f i l e, ' i ni f i l e' ) , ' ^\ [ . * \ ] $' ) ; } f unct i on cur r ent ( ) { r et ur n subst r ( par ent : : key( ) , 1, - 1) ; } f unct i on key( ) { r et ur n subst r ( par ent : : key( ) , 1, - 1) ; } } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 106
<?php i f ( ! cl ass_exi st s( ' KeyFi l t er ' , f al se) ) { r equi r e_once( ' keyf i l t er . i nc' ) ; } i f ( ! cl ass_exi st s( ' I ni G r oups' , f al se) ) { r equi r e_once( ' i ni gr oups. i nc' ) ; } $i t = new I ni G r oups( $ar gv[ 1] ) ; i f ( $ar gc>2) { $i t = new KeyFi l t er ( $i t , $ar gv[ 2] ) ; } f or each( $i t as $gr oup) { echo $gr oup . " \ n" ; } ?>
Avoid calling __aut ol oad( )
Marcus Börger Introduction to Object-oriented programming with PHP 107
Filtering Handling recursion Limiting
Marcus Börger Introduction to Object-oriented programming with PHP 108
Marcus Börger Introduction to Object-oriented programming with PHP 109
A name A description of their problem A description of the solution An assessment of the pros and cons of the pattern
Marcus Börger Introduction to Object-oriented programming with PHP 110
Marcus Börger Introduction to Object-oriented programming with PHP 111
Marcus Börger Introduction to Object-oriented programming with PHP 112
f or each( $ent r i es as $ent r y) { echo $ent r y; }
Marcus Börger Introduction to Object-oriented programming with PHP 113
Marcus Börger Introduction to Object-oriented programming with PHP 114
Marcus Börger Introduction to Object-oriented programming with PHP 115
<?php cl ass SO AP_Cl i ent { publ i c $wsdl ; publ i c f unct i on __const r uct ( $endpoi nt ) { $t hi s- >wsdl = W SDLM anager : : get ( $endpoi nt ) ; } publ i c f unct i on __cal l ( $m et hod, $ar gs) { $por t = $t hi s- >wsdl - >get Por t For O per at i on( $m et hod) ; $t hi s- >endpoi nt =$t hi s- >wsdl - >get Por t Endpoi nt ( $por t ) ; $r equest = SO AP_Envel ope: : r equest ( $t hi s- >wsdl ) ; $r equest - >addM et hod( $m et hod, $ar gs) ; $dat a = $r equest - >saveXM L( ) ; r et ur n SO AP_Envel ope: : par se( $t hi s- >endpoi nt , $dat a) ; } } ?>
Marcus Börger Introduction to Object-oriented programming with PHP 116
Marcus Börger Introduction to Object-oriented programming with PHP 117
$obser ver s[ ] = $obser ver ;
f or each( $obser ver s as $o) { i f ( $o === $obser ver ) r et ur n; } $obser ver s[ ] = $obser ver ;
f or each( $obser ver s as $k => $o) { i f ( $o === $obser ver ) { unset ( $obser ver [ $k] ) ; br eak; } }
Marcus Börger Introduction to Object-oriented programming with PHP 118
cl ass O bj ect St or age { pr ot ect ed $st or age = ar r ay( ) ; f unct i on at t ach( $obj ) { f or each( $t hi s- >st or age as $o) { i f ( $o === $obj ) r et ur n; } $t hi s- >st or age[ ] = $obj ; } f unct i on det at ch( $obj ) { f or each( $t hi s- >st or age as $k => $o) { i f ( $o === $obj ) { unset ( $t hi s- >st or age[ $k] ) ; r et ur n; } } } }
Marcus Börger Introduction to Object-oriented programming with PHP 119
cl ass O bj ect St or age { pr ot ect ed $st or age = ar r ay( ) ; f unct i on at t ach( $obj ) { $t hi s- >st or age[ spl _obj ect _hash( $obj ) ] = $obj ; } f unct i on det at ch( $obj ) { unset ( $t hi s- >st or age[ spl _obj ect _hash( $obj ) ] ) ; } }
Marcus Börger Introduction to Object-oriented programming with PHP 120
cl ass M ySubj ect i m pl em ent s Subj ect { pr ot ect ed $obser ver s; publ i c f unct i on __const r uct ( ) { $t hi s- >obser ver = new O bj ect St or age; } publ i c f unct i on at t ach( O bser ver $o) { $t hi s- >obser ver s- >at t ach( $o) ; } publ i c f unct i on det ach( O bser ver $o) { $t hi s- >obser ver s- >det ach( $o) ; } publ i c f unct i on not i f y( ) { f or each( $t hi s- >obser ver s as $o) $o- >updat e( $t hi s) ; } } cl ass M yO bser ver i m pl em ent s O bser ver { publ i c f unct i on updat e( Subj ect $s) { / / do l oggi ng or som e ot her act i on } }
Marcus Börger Introduction to Object-oriented programming with PHP 121
php –r ' pr i nt _r ( ar r ay_keys( spl _cl asses( ) ) ) ; '
php - - r c <Cl ass>
php - - r f <Funct i on>
php - - r e <Ext ensi on>
php - - r i <Ext ensi on>
Marcus Börger Introduction to Object-oriented programming with PHP 122