php chapter10

Upload: dsunte-wilson

Post on 07-Aug-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/20/2019 PHP Chapter10

    1/52

    Chapter 10

    Developing

    Object-Oriented PHP

     

  • 8/20/2019 PHP Chapter10

    2/52

     2

    Objectives

    In this chapter, you ill!

    " #tudy object-oriented progra$$ing concepts

    " %se objects in PHP scripts

    " Declare data $e$bers in classes

    " &or' ith class $e$ber (unctions

  • 8/20/2019 PHP Chapter10

    3/52

     )

    Introduction to Object-OrientedProgra$$ing

    " Object-oriented programming *OOP+ re(ersthe concept o( $erging related variables and(unctions into a single inter(ace

    "  n object re(ers to progra$$ing code and datathat can be treated as an individual unit orco$ponent

    "Objects are o(ten also called components

  • 8/20/2019 PHP Chapter10

    4/52

     

    Introduction to Object-OrientedProgra$$ing *continued+

    " Data re(ers to in(or$ation contained ithinvariables or other types o( storage structures

    " .he (unctions associated ith an object are

    called methods" .he variables that are associated ith an object

    are called properties or attributes

    " Popular object-oriented progra$$ing languagesinclude C//, ava, and isual asic

  • 8/20/2019 PHP Chapter10

    5/52

     3

    Introduction to Object-OrientedProgra$$ing *continued+

    Figure 10-1 Accounting program

  • 8/20/2019 PHP Chapter10

    6/52

     4

    %nderstanding 5ncapsulation

    " Objects are encapsulated 6 all code andre7uired data are contained ithin the objectitsel( 

    " 5ncapsulated objects hide all internal codeand data

    "  n interface re(ers to the $ethods andproperties that are re7uired (or a sourceprogra$ to co$$unicate ith an object

  • 8/20/2019 PHP Chapter10

    7/52

     8

    %nderstanding 5ncapsulation*continued+

    " 5ncapsulated objects allo users to see only the$ethods and properties o( the object that youallo the$ to see

    " 5ncapsulation reduces the co$ple9ity o( thecode

    " 5ncapsulation prevents other progra$$ers (ro$accidentally introducing a bug into a progra$, orstealing code

  • 8/20/2019 PHP Chapter10

    8/52

     :

    Object-Oriented Progra$$ingand Classes

    " .he code, $ethods, attributes, and otherin(or$ation that $a'e up an object areorgani;ed into classes

    "  n instance is an object that has been created(ro$ an e9isting class

    " Creating an object (ro$ an e9isting class iscalled instantiating the object

    "  n object inherits its $ethods and properties(ro$ a class < it ta'es on the characteristics o(the class on hich it is based

  • 8/20/2019 PHP Chapter10

    9/52

     =

    %sing Objects in PHP #cripts

    " Declare an object in PHP by using the new operator ith a class constructor 

    "   class constructor  is a special (unction ith

    the sa$e na$e as its class that is calledauto$atically hen an object (ro$ the class isinstantiated

    " .he synta9 (or instantiating an object is!

    $ObjectName = new ClassName();

  • 8/20/2019 PHP Chapter10

    10/52

     10

    %sing Objects in PHP #cripts*continued+

    "  (ter an object is instantiated, use a hyphen anda greater-than sy$bol *->+ to access the$ethods and properties contained in the object

    " .ogether, these to characters are re(erred to asmember selection notation

    " &ith $e$ber selection notation, one or $orecharacters are appended to an object, (olloedby the na$e o( a $ethod or property

  • 8/20/2019 PHP Chapter10

    11/52

     11

    %sing Objects in PHP #cripts*continued+

    " &ith $ethods, include a set o( parentheses atthe end o( the $ethod na$e, just as ith(unctions

    " >i'e (unctions, $ethods can also acceptargu$ents

    $Checking->getBalance();

    $CheckNumber = 1022;

    $Checking->getCheckAmount($CheckNumber);

  • 8/20/2019 PHP Chapter10

    12/52

     12

    &or'ing ith DatabaseConnections as Objects

    "  ccess ?y#@> database connections as objectsby instantiating an object (ro$ the m!"li class

    " .o connect to a ?y#@> database server using

    procedural synta9!  $#BConnect = m!"lconnect(%&h&'b% %'ongo!!elin%

    %ro!ebu'%);

      m!"l!elect'b(%reale!tate% $#BConnect);

    " .o connect to the ?y#@> database server usingobject-oriented style!

      $#BConnect = new m!"li(%&h&'b% %'ongo!!elin%

    %ro!ebu'% %reale!tate%);

  • 8/20/2019 PHP Chapter10

    13/52

     1)

    Handling ?y#@> 5rrors

    " .his state$ent uses the m!"li() constructor(unction to instantiate a m!"li class objectna$ed $#BConnect

      $#BConnect = new m!"li(%&h&'b% %'go!!elin%%ro!ebu'%);

    " .o e9plicitly close the database connection, usethe clo!e() $ethod o( the m!"li class $#BConnect->clo!e();

  • 8/20/2019 PHP Chapter10

    14/52

     1

    Handling ?y#@> 5rrors *continued+

    " &ith object-oriented style, chec' hether a valueis assigned to the m!"liconnecterrno() or m!"liconnecterror() (unctions

    $#BConnect = new m!"li(%&h&*'b% %'go!!elin% %ro!ebu'%);

    i+ ($#BConnect->connecterrno),

      echo(%&>.nable to connect to the 'ataba!e!er/er*&>%

      * %&>rror co'e % * $#BConnect->connecterrno

      * % % * $#BConnect->connecterror* %&>3n%;

    el!e ,co'e to e4ecute i+ the connection +ail!

    5

  • 8/20/2019 PHP Chapter10

    15/52

     13

    59ecuting #@> #tate$ents

    " &ith object-oriented style, use the "uer() $ethod o( the m!"li class

    " .o return the (ields in the current ro o( a resultset

    into an inde9ed array use! 6 .he +etchrow() $ethod o( the m!"li class

    " .o return the (ields in the current ro o( a resultsetinto an associative array use!

     6 .he +etcha!!oc() $ethod o( the m!"li class

  • 8/20/2019 PHP Chapter10

    16/52

     14

    59ecuting #@> #tate$ents*continued+

    $6ableName = %com&ancar!%;

    $789!tring = %79C6 : % *

      %th>ileageth>th>earth>tr>3n%;

  • 8/20/2019 PHP Chapter10

    17/52

     18

    59ecuting #@> #tate$ents*continued+

    A

    while (($t'>,$,$,$,$,$

  • 8/20/2019 PHP Chapter10

    18/52

     1:

    De(ining Custo$ PHP Classes

    " Data structure re(ers to a syste$ (or organi;ingdata

    " .he (unctions and variables de(ined in a class

    are called class members" Class variables are re(erred to as data

    members or member variables 

    " Class (unctions are re(erred to as member  functions or function members

  • 8/20/2019 PHP Chapter10

    19/52

     1=

    De(ining Custo$ PHP Classes*continued+

    " Classes! 6 Help $a'e co$ple9 progra$s easier to $anage

     6 Hide in(or$ation that users o( a class do not need

    to access or 'no about 6 ?a'e it easier to reuse code or distribute your

    code to others (or use in their progra$s

    " Inherited characteristics allo you to build ne

    classes based on e9isting classes ithouthaving to rerite the code contained in thee9isting one

  • 8/20/2019 PHP Chapter10

    20/52

     20

    Creating a Class De(inition

    " .o create a class in PHP, use the cla!! 'eyord to rite a class de(inition

    "   class definition contains the data $e$bers

    and $e$ber (unctions that $a'e up the class" .he synta9 (or de(ining a class is!

    cla!! ClassName ,

    data member and member function definitions5

  • 8/20/2019 PHP Chapter10

    21/52

     21

    Creating a Class De(inition*continued+

    " .he ClassName portion o( the class de(inition isthe na$e o( the ne class

    " Class na$es usually begin ith an uppercase

    letter to distinguish the$ (ro$ other identi(iers" &ithin the classBs curly braces, declare the data

    type and (ield na$es (or each piece o(in(or$ation stored in the structure

      cla!! BankAccount ,  data member and member function definitions

      5

      $Checking = new BankAccount();

  • 8/20/2019 PHP Chapter10

    22/52

     22

    Creating a Class De(inition*continued+

    " Class na$es in a class de(inition are not(olloed by parentheses, as are (unctionna$es in a (unction de(inition

    $Checking = new BankAccount();echo ?6he $Checking obGect i! in!tantiate' +rom the ?

    * get_class($Checking) * % cla!!*&>%;

    " %se the in!tanceo+ operator to deter$inehether an object is instantiated (ro$ a given

    class" %se the cla!!e4i!t!() to deter$ine i( a

    class e9ists

  • 8/20/2019 PHP Chapter10

    23/52

     2)

    #toring Classes in 59ternal iles

    " PHP provides the (olloing (unctions that alloyou to use e9ternal (iles in your PHP scripts!H inclu'e() 

    H re"uire()H inclu'eonce()

    H re"uireonce()

    " ou pass to each (unction the na$e and path o(the e9ternal (ile you ant to use

  • 8/20/2019 PHP Chapter10

    24/52

     2

    #toring Classes in 59ternal iles*continued+

    I inclu'e() and re"uire() (unctions bothinsert the contents o( an e9ternal (ile, called aninclude file, into a PHP script

    I inclu'eonce() and re"uireonce() (unctions only include an e9ternal (ile onceduring the processing o( a script

    "  ny PHP code $ust be contained ithin a PHPscript section *J&h& *** J>) in an e9ternal(ile

  • 8/20/2019 PHP Chapter10

    25/52

     23

    Collecting Earbage

    " Garbage collection re(ers to cleaning up orreclai$ing $e$ory that is reserved by aprogra$

    " PHP 'nos hen your progra$ no longer needsa variable or object and auto$atically cleans upthe $e$ory (or you

    " .he one e9ception is ith open databaseconnections

  • 8/20/2019 PHP Chapter10

    26/52

     24

    In(or$ation Hiding

    " Information hiding states that any class$e$bers that other progra$$ers, so$eti$escalled clients, do not need to access or 'noabout should be hidden

    " Helps $ini$i;e the a$ount o( in(or$ation thatneeds to pass in and out o( an object

    " Feduces the co$ple9ity o( the code that clientssee

    " Prevents other progra$$ers (ro$ accidentallyintroducing a bug into a progra$ by $odi(ying aclassBs internal or'ings

  • 8/20/2019 PHP Chapter10

    27/52

     28

    %sing ccess #peci(iers

    " Access specifiers control a clientBs access toindividual data $e$bers and $e$ber (unctions

    " .here are three levels o( access speci(iers in

    PHP! &ublic, &ri/ate, and &rotecte'" .he public access specifier  allos anyone tocall a classBs $e$ber (unction or to $odi(y andretrieve a data $e$ber 

  • 8/20/2019 PHP Chapter10

    28/52

     2:

    %sing ccess #peci(iers*continued+

    " .he private access specifier  prevents clients(ro$ calling $e$ber (unctions or accessing data$e$bers and is one o( the 'ey ele$ents inin(or$ation hiding

    " Private access does not restrict a classBs internalaccess to its on $e$bers

    " Private access restricts clients (ro$ accessing

    class $e$bers

  • 8/20/2019 PHP Chapter10

    29/52

     2=

    %sing ccess #peci(iers*continued+

    " Include an access speci(ier at the beginning o( adata $e$ber declaration state$ent

    cla!! BankAccount ,

       public $Balance = 0;

    5

    "  lays assign an initial value to a data $e$berhen you (irst declare it

    cla!! BankAccount ,

      &ublic $Balance = 1 K 2;

    5

  • 8/20/2019 PHP Chapter10

    30/52

     )0

    #eriali;ing Objects

    " Serialiation re(ers to the process o( convertingan object into a string that you can store (orreuse

    " #eriali;ation stores both data $e$bers and$e$ber (unctions into strings

    " .o seriali;e an object, pass an object na$e tothe !erialiLe() (unction

    $7a/e'Account = !erialiLe($Checking);

  • 8/20/2019 PHP Chapter10

    31/52

     )1

    #eriali;ing Objects *continued+

    " .o convert seriali;ed data bac' into an object,you use the un!erialiLe() (unction

    $Checking = un!erialiLe($7a/e'Account);

    " #eriali;ation is also used to store the data inlarge arrays

    " .o use seriali;ed objects beteen scripts, assigna seriali;ed object to a session variable

      !e!!ion!tart();

      $777MN(?7a/e'Account?) = !erialiLe($Checking);

  • 8/20/2019 PHP Chapter10

    32/52

     )2

    &or'ing ith ?e$ber unctions

    " Create public $e$ber (unctions (or any(unctions that clients need to access

    " Create private $e$ber (unctions (or any

    (unctions that clients do not need to access"  ccess speci(iers control a clientBs access to

    individual data $e$bers and $e$ber (unctions

  • 8/20/2019 PHP Chapter10

    33/52

     ))

    &or'ing ith ?e$ber unctions*continued+

    cla!! BankAccount ,&ublic $Balance = OP*20;

     public function withdrawal($Amount) {

    $this->alance -! $Amount"

    #

    5

    i+ (cla!!e4i!t!(%BankAccount%))

    $Checking = new BankAccount();

    el!e

    e4it(%&>6he BankAccount cla!! i! not a/ailable&>%);

    &rint+(%&>our checking account balance i! $@*2+*&>%

    $Checking->Balance);

    $Ca!h = 200;

    $Checking->withdrawal(%%)"

    &rint+(%&>A+ter with'rawing $@*2+ our checking account balance

    i! $@*2+*&>% $Ca!h $Checking->Balance);

  • 8/20/2019 PHP Chapter10

    34/52

     )

    %sing the $thi! Fe(erence

    " Outside o( a class, re(er to the $e$bers o( theobject using the na$e o( the object, the $e$berselection nation *-+, and the na$e o( the (unctionor variable

    " &ithin a class (unction de(inition, use Gthis tore(er to the current object o( the class

     $thi!->AccountNumber = 0;

  • 8/20/2019 PHP Chapter10

    35/52

     )3

    Initiali;ing ith Constructorunctions

    "   constructor function is a special (unction thatis called auto$atically hen an object (ro$ aclass is instantiatedcla!! BankAccount ,

    &ri/ate $AccountNumber;

    &ri/ate $Cu!tomerName;

    &ri/ate $Balance;

    +unction con!truct() ,

    $thi!->AccountNumber = 0;

    $thi!->Balance = 0;

    $thi!->Cu!tomerName = %%;

    5

    5

  • 8/20/2019 PHP Chapter10

    36/52

     )4

    Initiali;ing ith Constructorunctions *continued+

    " .he con!truct() (unction ta'esprecedence over a (unction ith the sa$e na$eas the class

    " Constructor (unctions are co$$only used inPHP to handle database connection tas's

  • 8/20/2019 PHP Chapter10

    37/52

     )8

    Cleaning %p ith Destructorunctions

    "   de(ault constructor (unction is called hen aclass object is (irst instantiated

    "   destructor  (unction is called hen the object

    is destroyed"   destructor (unction cleans up any resources

    allocated to an object a(ter the object isdestroyed

  • 8/20/2019 PHP Chapter10

    38/52

     ):

    Cleaning %p ith Destructorunctions *continued+

    "   destructor (unction is co$$only called in toays!

     6 &hen a script ends

     6 &hen you $anually delete an object iththe un!et() (unction

    " .o add a destructor (unction to a PHP class,create a (unction na$ed 'e!truct()

  • 8/20/2019 PHP Chapter10

    39/52

     )=

    Cleaning %p ith Destructorunctions *continued+

    +unction con!truct() ,

    $#BConnect = new m!"li(%&h&'b%

    %'ongo!!elin%%ro!ebu'%

    %reale!tate%);

    5

    function __destruct() {

    $&Connect->close()"

    #

  • 8/20/2019 PHP Chapter10

    40/52

     0

    &riting ccessor unctions

    " Accessor functions are public $e$ber(unctions that a client can call to retrieve or$odi(y the value o( a data $e$ber 

    "  ccessor (unctions o(ten begin ith the ordsset or get

    " #et (unctions $odi(y data $e$ber values

    "Eet (unctions retrieve data $e$ber values

  • 8/20/2019 PHP Chapter10

    41/52

     1

    &riting ccessor unctions*continued+

    cla!! BankAccount ,

    &ri/ate $Balance = 0;

    &ublic +unction !etBalance($NewQalue) ,

    $thi!->Balance = $NewQalue;

    5

    &ublic +unction getBalance() ,

    return $thi!->Balance;5

    5

    i+ (cla!!e4i!t!(%BankAccount%))

    $Checking = new BankAccount();

    el!e

    e4it(%&>6he BankAccount cla!! i! not a/ailable&>%);

    $Checking->!etBalance(100);

    echo %&>our checking account balance i! %

    * $Checking->getBalance() * %&>3n%;

  • 8/20/2019 PHP Chapter10

    42/52

     2

    #eriali;ation unctions

    " &hen you seriali;e an object ith the!erialiLe() (unction, PHP loo's in theobjectBs class (or a special (unction na$ed

    !lee&()" .he pri$ary reason (or including a !lee&() 

    (unction in a class is to speci(y hich data$e$bers o( the class to seriali;e

  • 8/20/2019 PHP Chapter10

    43/52

     )

    #eriali;ation unctions *continued+

    " I( you do not include a !lee&() (unction inyour class, the !erialiLe() (unction seriali;esall o( its data $e$bers

    +unction !lee&() ,

    $7erialQar! = arra(?Balance?);

    return $7erialQar!;

    5

    " &hen the un!erialiLe() (unction e9ecutes,

    PHP loo's in the objectBs class (or a special(unction na$ed wakeu&()

  • 8/20/2019 PHP Chapter10

    44/52

     

    #u$$ary

    " .he ter$ object-oriented programming*OOP+ re(ers to the creation o( reusableso(tare objects that can be easily incorporated

    into $ultiple progra$sJ .he ter$ objectspeci(ically re(ers to progra$$ing code and datathat can be treated as an individual unit orco$ponent *object+

    " .he ter$ data re(ers to in(or$ation containedithin variables or other types o( storagestructures

  • 8/20/2019 PHP Chapter10

    45/52

  • 8/20/2019 PHP Chapter10

    46/52

     4

    #u$$ary *continued+

    " In object-oriented progra$$ing, the code,$ethods, attributes, and other in(or$ation that$a'e up an object are organi;ed into classes

    "  n instance is an object that has been created(ro$ an e9isting classJ &hen you create anobject (ro$ an e9isting class, you areinstantiating the object” 

  • 8/20/2019 PHP Chapter10

    47/52

     8

    #u$$ary *continued+

    "   particular instance o( an object inherits its$ethods and properties (ro$ a class

  • 8/20/2019 PHP Chapter10

    48/52

     :

    #u$$ary *continued+

    " .he (unctions and variables de(ined in a classare called class membersJ Class variables arere(erred to as data members or member

    variables, hereas class (unctions are re(erredto as member functions or (unction members

    "   class definition contains the data $e$bersand $e$ber (unctions that $a'e up the class

  • 8/20/2019 PHP Chapter10

    49/52

     =

    #u$$ary *continued+

    " PHP provides the (olloing (unctions that alloyou to use e9ternal (iles in your PHP scripts!inclu'e(), re"uire(), inclu'eonce(),

    and re"uireonce()" .he principle o( information hiding states that

    class $e$bers should be hidden hen otherprogra$$ers do not need to access or 'no

    about the$" Access specifiers control a clientBs access to

    individual data $e$bers and $e$ber (unctions

  • 8/20/2019 PHP Chapter10

    50/52

     30

    #u$$ary *continued+

    " Serialiation re(ers to the process o( convertingan object into a string that you can store (orreuse

    "   constructor function is a special (unction thatis called auto$atically hen an object (ro$ aclass is instantiated

    "   destructor function cleans up any resources

    allocated to an object a(ter the object isdestroyed

  • 8/20/2019 PHP Chapter10

    51/52

     31

    #u$$ary *continued+

    " Accessor functions are public $e$ber(unctions that a client can call to retrieve thevalue o( a data $e$ber 

    " !utator functions are public $e$ber (unctionsthat a client can call to $odi(y the value o( adata $e$ber 

  • 8/20/2019 PHP Chapter10

    52/52

    32

    #u$$ary *continued+

    " &hen you seriali;e an object ith the!erialiLe() (unction, PHP loo's in theobjectBs class (or a special (unction na$ed

    !lee&(), hich you can use to per(or$$any o( the sa$e tas's as a destructor (unction

    " &hen the un!erialiLe() (unction e9ecutes,PHP loo's in the objectBs class (or a special

    (unction na$ed wakeu&(), hich you canuse to per(or$ $any o( the sa$e tas's as aconstructor (unction