SlideShare uma empresa Scribd logo
1 de 64
Baixar para ler offline
Object Oriented Programming
About OOP
OOP

 • Object Oriented Programming

 • Spot it where there are -> notations

 • Allows us to keep data and functionality together

 • Used to organise complex programs




                                                       3
OOP

 • Object Oriented Programming

 • Spot it where there are -> notations

 • Allows us to keep data and functionality together

 • Used to organise complex programs

 • Basic building block are simple (I promise!)




                                                       3
Classes vs Objects
Class

The class is a recipe, a blueprint
class Table {
}




                                     5
Object

The object is a tangible thing
$coffee_table = new Table();


The $coffee_table is an Object, an "instance" of Table




                                                         6
Object Properties

Can be defined in the class
class Table {
  public $legs;
}


Or set as we go along
$coffee_table->legs = 4;




                             7
Object Methods

These are "functions", with a fancy name
class Table {
    public $legs;

    public function getLegCount() {
        return $this->legs;
    }
}


$coffee_table = new Table();
$coffee_table->legs = 4;
echo $coffee_table->getLegCount(); // 4




                                           8
Static Methods

We can call methods without instantiating a class

  • $this is not available in a static method

  • use the :: notation (paamayim nekudotayim)

  • used where we don’t need object properties


class Table {
    public static function getColours() {
        return array("beech", "birch", "mahogany");
    }
}


$choices = Table::getColours();




                                                      9
Accessing Classes

Just like library files, we use include and require to bring class code
into our applications.

We can also use autoloading if our classes are predictably named.
function __autoload($classname) {

        if(preg_match('/[a-zA-Z]+Controller$/',$classname)) {
                include('../controllers/' . $classname . '.php');
                return true;
        } elseif(preg_match('/[a-zA-Z]+Model$/',$classname)) {
                include('../models/' . $classname . '.php');
                return true;
        } elseif(preg_match('/[a-zA-Z]+View$/',$classname)) {
                include('../views/' . $classname . '.php');
                return true;
        }
}

No need to include/require if you have autoloading


                                                                         10
Objects and References

Objects are always passed by reference
$red_table = new Table();
$red_table->legs = 4;

$other_table = $red_table;
$other_table->legs = 3;

echo $red_table->legs; // output: 3


Objects behave differently from variables

   • objects are always references, when assigned and when passed
     around

   • variables are copied when they are passed into a function

   • you can pass by reference by using &



                                                                    11
Copying Objects

If you actually want to copy an object, you need to use the clone keyword
$red_table = new Table();
$red_table->legs = 4;

$other_table = clone $red_table;
$other_table->legs = 3;

echo $red_table->legs; // output: 4




                                                                            12
Inheritance
Inheritance

OOP supports inheritance

  • similar classes can share a parent and override features

  • improves modularity, avoids duplication

  • classes can only have one parent (unlike some other languages)

  • classes can have many children

  • there can be as many generations of inheritance as we need




                                                                     14
How NOT to Design Class Hierarchies

   • create one class per database table

   • instantiate one object of each class

   • pass all required data in as parameters (or globals!)

   • never use $this


... note that the title says "NOT"




                                                             15
Designing Class Hierarchies

  • identify "things" in your system (users, posts, orders)

  • what qualities do they share?

  • where are objects similar? Or different?

  • in MVC systems, remember that controllers and views are often
    objects too




                                                                    16
Inheritance Examples

class Table {

    public $legs;

    public function getLegCount() {
        return $this->legs;
    }
}

class DiningTable extends Table {}


$newtable = new DiningTable();
$newtable->legs = 6;
echo $newtable->getLegCount(); // 6




                                      17
Access Modifiers
Visibility

We can control which parts of a class are available and where:

   • public: always available, everywhere

   • private:* only available inside this class

   • protected: only available inside this class and descendants

This applies to both methods and properties

* use with caution! Protected is almost always a better choice




                                                                   19
Protected Properties

class Table {
    protected $legs;

    public function getLegCount() {
        return $this->legs;
    }

    public function setLegCount($legs) {
        $this->legs = $legs;
        return true;
    }
}


$table = new Table();
$table->legs = 4;

// Fatal error: Cannot access protected property Table::$legs in /.../




                                                                   20
Protected Properties

class Table {
    protected $legs;

    public function getLegCount() {
        return $this->legs;
    }

    public function setLegCount($legs) {
        $this->legs = $legs;
        return true;
    }
}


$table = new Table();
$table->setLegCount(4);

echo $table->getLegCount();


It is common to use "getters" and "setters" in this way, especially if you are
a Java programmer                                                                21
Protected Methods

Access modifiers for methods work exactly the same way:
class Table {
    protected function getColours() {
        return array("beech", "birch", "mahogany");
    }
}


class DiningTable extends Table {
    public function colourChoice() {
        return parent::getColours();
    }
}

If Table::getColours() were private, DiningTable would think that
method was undefined




                                                                    22
Object Keywords

 • parent: the class this class extends




                                          23
Object Keywords

 • parent: the class this class extends

 • self: this class, usually used in a static context, instead of $this

     • WARNING: in extending classes, this resolves to where it was
       declared
     • This was fixed in PHP 5.3 by "late static binding"




                                                                          23
Object Keywords

 • parent: the class this class extends

 • self: this class, usually used in a static context, instead of $this

     • WARNING: in extending classes, this resolves to where it was
       declared
     • This was fixed in PHP 5.3 by "late static binding"

 • static: the class in which the code is being used

     • Just like self but actually works :)




                                                                          23
Identifying Objects
The instanceOf Operator

To check whether an object is of a particular class, use instanceOf
$table = new DiningTable();

if($table instanceOf DiningTable) {
    echo "a dining tablen";
}

if($table instanceOf Table) {
    echo "a tablen";
}


InstanceOf will return true if the object:

   • is of that class

   • is of a child of that class

   • implements that interface (more on interfaces later)


                                                                      25
Type Hinting

We have type hinting in PHP for complex types. So we can do:
function moveFurniture(Table $table) {
    $table->move();
    // imagine something more exciting
    return true;
}


PHP will error unless the argument:

   • is of that class

   • is of a child of that class

   • implements that class (more on interfaces later)

... look familiar?




                                                               26
Comparing Objects

 • Comparison ==

     • objects must be of the (exact) same class
     • objects must have identical properties

 • Strict comparison ===

     • both arguments must refer to the same object




                                                      27
Magical Mystery Tour (of Magic
          Methods)
Magic Methods

 • two underscores in method name

 • allow us to override default object behaviour

 • really useful for Design Patterns and solving tricky problems




                                                                   29
Constructors

  • __construct: called when a new object is instantiated

      • declare any parameters you like
      • usually we inject dependencies
      • perform any other setup

$blue_table = new BlueTable();




                                                            30
Destructors

 • __destruct: called when the object is destroyed

     • good time to close resource handles




                                                     31
Fake Properties

When we access a property that doesn’t exist, PHP calls __get() or
__set() for us
class Table {

    public function __get($property) {
        // called if we are reading
        echo "you asked for $propertyn";
    }

    public function __set($property, $value) {
        // called if we are writing
        echo "you tried to set $property to $valuen";
    }
}

$table = new Table();

$table->legs = 5;

echo "table has: " . $table->legs . "legsn";

                                                                     32
Fake Methods

PHP calls __call when we call a method that doesn’t exist
class Table {
    public function shift($x, $y) {
        // the table moves
        echo "shift table by $x and $yn";
    }

    public function __call($method, $arguments) {
        // look out for calls to move(), these should be shift()
        if($method == "move") {
            return $this->shift($arguments[0], $arguments[1]);
        }
    }
}

$table = new Table();
$table->shift(3,5); // shift table by 3 and 5
$table->move(4,9); // shift table by 4 and 9

There is an equivalent function for static calls, __callStatic()

                                                                   33
Serialising Objects

We can control what happens when we serialize and unserialize
objects
class Table {
}

$table = new Table();
$table->legs = 4;
$table->colour = "red";

echo serialize($table);
// O:5:"Table":2:{s:4:"legs";i:4;s:6:"colour";s:3:"red";}




                                                                34
Serialising Objects

  • __sleep() to specify which properties to store

  • __wakeup() to put in place any additional items on unserialize

class Table {
    public function __sleep() {
        return array("legs");
    }
}

$table = new Table();
$table->legs = 7;
$table->colour = "red";

$data = serialize($table);
echo $data;
// O:5:"Table":1:{s:4:"legs";i:7;}




                                                                     35
Serialising Objects

  • __sleep() to specify which properties to store

  • __wakeup() to put in place any additional items on unserialize

class Table {
    public function __wakeup() {
        $this->colour = "wood";
    }
}

echo $data;
$other_table = unserialize($data);
print_r($other_table);

/* Table Object
(
    [legs] => 7
    [colour] => wood
) */


                                                                     36
Magic Tricks: clone

Control the behaviour of cloning an object by defining __clone()

  • make it return false to prevent cloning (for a Singleton)

  • recreate resources that shouldn’t be shared




                                                                  37
Magic Tricks: toString

Control what happens when an object cast to a string. E.g. for an
exception
class TableException extends Exception {
    public function __toString() {
        return '** ' . $this->getMessage() . ' **';
    }
}

try {
    throw new TableException("it wobbles!");
} catch (TableException $e) {
    echo $e;
}

// output: ** it wobbles! **

The default output would be
exception ’TableException’ with message ’it wobbles!’   in
/.../tostring.php:7 Stack trace:



                                                                    38
Exceptions
Exceptions are Objects

Exceptions are fabulous




                          40
Exceptions are Objects

Exceptions are fabulous
They are pretty good use of OOP too!

  • Exceptions are objects

  • Exceptions have properties

  • We can extend exceptions to make our own




                                               40
Raising Exceptions

In PHP, we can throw any exception, any time.
function addTwoNumbers($a, $b) {
    if(($a == 0) || ($b == 0)) {
        throw new Exception("Zero is Boring!");
    }

    return $a + $b;
}

echo addTwoNumbers(3,2); // 5
echo addTwoNumbers(5,0); // error!!



Fatal error: Uncaught exception ’Exception’ with message ’Zero is Boring!’ in /
Stack trace:
#0 /.../exception.php(12): addTwoNumbers(5, 0)
#1 {main}
    thrown in /.../exception.php on line 5




                                                                           41
Catching Exceptions

Exceptions are thrown, and should be caught by our code - avoid Fatal
Errors!
function addTwoNumbers($a, $b) {
    if(($a == 0) || ($b == 0)) {
        throw new Exception("Zero is Boring!");
    }

    return $a + $b;
}

try {
    echo addTwoNumbers(3,2);
    echo addTwoNumbers(5,0);
} catch (Exception $e) {
    echo "FAIL!! (" . $e->getMessage() . ")n";
}
// there is no "finally"

// output: 5FAIL!! (Zero is Boring!)


                                                                        42
Catching Exceptions

Exceptions are thrown, and should be caught by our code - avoid Fatal
Errors!
function addTwoNumbers($a, $b) {
    if(($a == 0) || ($b == 0)) {
        throw new Exception("Zero is Boring!");
    }

    return $a + $b;
}

try {
    echo addTwoNumbers(3,2);
    echo addTwoNumbers(5,0);
} catch (Exception $e) {
    echo "FAIL!! (" . $e->getMessage() . ")n";
}
// there is no "finally"

// output: 5FAIL!! (Zero is Boring!)

Did you spot the typehinting??
                                                                        43
Extending Exceptions

Make your own exceptions, and be specific when you catch
class DontBeDaftException extends Exception {
}

function tableColour($colour) {
    if($colour == "orange" || $colour == "spotty") {
        throw new DontBeDaftException($colour . 'is not acceptable');
    }
    echo "The table is $colourn";
}

try {
    tableColour("blue");
    tableColour("orange");
} catch (DontBeDaftException $e) {
    echo "Don't be daft! " . $e->getMessage();
} catch (Exception $e) {
    echo "The sky is falling in! " . $e->getMessage();
}



                                                                   44
Hands up if you’re still alive
Abstraction
Abstract Classes

Abstract classes are

  • incomplete

  • at least partially incomplete




                                    47
Abstract Classes

Abstract classes are

  • incomplete

  • at least partially incomplete

  • we cannot instantiate them

  • if a class has an abstract method, the class must be marked abstract
    too

  • common in parent classes




                                                                           47
Abstract Examples

An abstract class:
abstract class Shape {
    abstract function draw($x, $y);
}

We can build on it, but must implement any abstract methods
class Circle extends Shape {
    public function draw($x, $y) {
        // imagine funky geometry stuff
        echo "circle drawn at $x, $yn";
    }
}

Any non-abstract methods are inherited as normal




                                                              48
Interfaces
Interfaces

  • prototypes of class methods

  • classes "implement" an interface

  • they must implement all these methods

  • the object equivalent of a contract

PHP does not have multiple inheritance




                                            50
Example Interface: Countable

This interface is defined in SPL, and it looks like this:
Interface Countable {
    public function count();
}

RTFM: http://uk2.php.net/manual/en/class.countable.php




                                                           51
Implementing Countable Interface

We can implement this interface in a class, so long as our class has a
count() method
class Table implements Countable {
    public function personArrived() {
        $this->people++;
        return true;
    }

    public function personLeft() {
        $this->people--;
        return true;
    }

    public function count() {
        return $this->people;
    }
}

$my_table = new Table();
$my_table->personArrived();
$my_table->personArrived();
echo count($my_table); // 2                                              52
Object Design by Composition

This is where interfaces come into their own

   • class hierarchy is more than inheritance

   • identify little blocks of functionality

   • each of these becomes an interface

   • objects implement as appropriate




                                                53
Polymorphism

A big word representing a small concept!

  • we saw typehints and instanceOf

  • classes identify as themselves, their parents or anything they
    implement

  • word roots:

       • poly: many
       • morph: body

Our object can appear to be more than one thing




                                                                     54
Questions?
Resources

 • PHP Manual http://php.net

     • start here: http://php.net/manual/en/language.oop5.php

 • Think Vitamin (Disclaimer: my posts!)

     •
         http://thinkvitamin.com/code/oop-with-php-finishing-tou

 • PHP Objects, Patterns and Practice Matt Zandstra (book)




                                                                56
Further Reading

Knwoing OOP means you can go on to learn/use:

  • PDO

  • SPL

  • Design Patterns




                                                57
Thanks
Image Credits

  •   http://www.flickr.com/photos/amiefedora/3897320577
  •
      http://www.flickr.com/photos/silkroadcollection/4886280049

  •   http://www.flickr.com/photos/dalbera/5336748810
  •   http://www.flickr.com/photos/stml/3625386561/
  •   http://www.flickr.com/photos/mikebaird/1958287914
  •   http://www.flickr.com/photos/dalbera/5336748810
  •   http://www.flickr.com/photos/mr_git/1118330301/
  •   http://www.flickr.com/photos/mafleen/1782135825




                                                              59

Mais conteúdo relacionado

Mais procurados (20)

Oop in-php
Oop in-phpOop in-php
Oop in-php
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
Php Oop
Php OopPhp Oop
Php Oop
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Oops in php
Oops in phpOops in php
Oops in php
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
Only oop
Only oopOnly oop
Only oop
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 

Destaque

Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 
Aula 8 php (intro, get e post)
Aula 8   php (intro, get e post)Aula 8   php (intro, get e post)
Aula 8 php (intro, get e post)andreluizlc
 
Frontend 'vs' Backend Getting the Right Mix
Frontend 'vs' Backend   Getting the Right MixFrontend 'vs' Backend   Getting the Right Mix
Frontend 'vs' Backend Getting the Right MixBob Paulin
 
Asic backend design
Asic backend designAsic backend design
Asic backend designkbipeen
 
Fundamentals of Web for Non-Developers
Fundamentals of Web for Non-DevelopersFundamentals of Web for Non-Developers
Fundamentals of Web for Non-DevelopersLemi Orhan Ergin
 
Web Application Development Fundamentals
Web Application Development FundamentalsWeb Application Development Fundamentals
Web Application Development FundamentalsMohammed Makhlouf
 
Tomcat and apache httpd training
Tomcat and apache httpd trainingTomcat and apache httpd training
Tomcat and apache httpd trainingFranck SIMON
 

Destaque (16)

Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Aula 8 php (intro, get e post)
Aula 8   php (intro, get e post)Aula 8   php (intro, get e post)
Aula 8 php (intro, get e post)
 
php Mailer
php Mailerphp Mailer
php Mailer
 
Frontend 'vs' Backend Getting the Right Mix
Frontend 'vs' Backend   Getting the Right MixFrontend 'vs' Backend   Getting the Right Mix
Frontend 'vs' Backend Getting the Right Mix
 
Local File Inclusion to Remote Code Execution
Local File Inclusion to Remote Code ExecutionLocal File Inclusion to Remote Code Execution
Local File Inclusion to Remote Code Execution
 
Beginning OOP in PHP
Beginning OOP in PHPBeginning OOP in PHP
Beginning OOP in PHP
 
Asic backend design
Asic backend designAsic backend design
Asic backend design
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
C vs c++
C vs c++C vs c++
C vs c++
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
APACHE TOMCAT
APACHE TOMCATAPACHE TOMCAT
APACHE TOMCAT
 
JSP
JSPJSP
JSP
 
Fundamentals of Web for Non-Developers
Fundamentals of Web for Non-DevelopersFundamentals of Web for Non-Developers
Fundamentals of Web for Non-Developers
 
Web Application Development Fundamentals
Web Application Development FundamentalsWeb Application Development Fundamentals
Web Application Development Fundamentals
 
Tomcat and apache httpd training
Tomcat and apache httpd trainingTomcat and apache httpd training
Tomcat and apache httpd training
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 

Semelhante a Object Oriented Programming in PHP

PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.pptrani marri
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3Nate Abele
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Bozhidar Boshnakov
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Anonymous Classes: Behind the Mask
Anonymous Classes: Behind the MaskAnonymous Classes: Behind the Mask
Anonymous Classes: Behind the MaskMark Baker
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPDemystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPAlena Holligan
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPAlena Holligan
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Alena Holligan
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 
Development Approach
Development ApproachDevelopment Approach
Development Approachalexkingorg
 

Semelhante a Object Oriented Programming in PHP (20)

PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
Dci in PHP
Dci in PHPDci in PHP
Dci in PHP
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Anonymous Classes: Behind the Mask
Anonymous Classes: Behind the MaskAnonymous Classes: Behind the Mask
Anonymous Classes: Behind the Mask
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
OOP
OOPOOP
OOP
 
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPDemystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHP
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
 
2012 03 08_dbi
2012 03 08_dbi2012 03 08_dbi
2012 03 08_dbi
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
Development Approach
Development ApproachDevelopment Approach
Development Approach
 

Mais de Lorna Mitchell

Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API DesignLorna Mitchell
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open SourceLorna Mitchell
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyLorna Mitchell
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knewLorna Mitchell
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Lorna Mitchell
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP StackLorna Mitchell
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source ControlLorna Mitchell
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service DesignLorna Mitchell
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishLorna Mitchell
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Implementing OAuth with PHP
Implementing OAuth with PHPImplementing OAuth with PHP
Implementing OAuth with PHPLorna Mitchell
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?Lorna Mitchell
 

Mais de Lorna Mitchell (20)

OAuth: Trust Issues
OAuth: Trust IssuesOAuth: Trust Issues
OAuth: Trust Issues
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API Design
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open Source
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and Money
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knew
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Join In With Joind.In
Join In With Joind.InJoin In With Joind.In
Join In With Joind.In
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
 
Going Freelance
Going FreelanceGoing Freelance
Going Freelance
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source Control
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service Design
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To Fish
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Implementing OAuth with PHP
Implementing OAuth with PHPImplementing OAuth with PHP
Implementing OAuth with PHP
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Example Presentation
Example PresentationExample Presentation
Example Presentation
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

Último

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dashnarutouzumaki53779
 

Último (20)

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dash
 

Object Oriented Programming in PHP

  • 3. OOP • Object Oriented Programming • Spot it where there are -> notations • Allows us to keep data and functionality together • Used to organise complex programs 3
  • 4. OOP • Object Oriented Programming • Spot it where there are -> notations • Allows us to keep data and functionality together • Used to organise complex programs • Basic building block are simple (I promise!) 3
  • 6. Class The class is a recipe, a blueprint class Table { } 5
  • 7. Object The object is a tangible thing $coffee_table = new Table(); The $coffee_table is an Object, an "instance" of Table 6
  • 8. Object Properties Can be defined in the class class Table { public $legs; } Or set as we go along $coffee_table->legs = 4; 7
  • 9. Object Methods These are "functions", with a fancy name class Table { public $legs; public function getLegCount() { return $this->legs; } } $coffee_table = new Table(); $coffee_table->legs = 4; echo $coffee_table->getLegCount(); // 4 8
  • 10. Static Methods We can call methods without instantiating a class • $this is not available in a static method • use the :: notation (paamayim nekudotayim) • used where we don’t need object properties class Table { public static function getColours() { return array("beech", "birch", "mahogany"); } } $choices = Table::getColours(); 9
  • 11. Accessing Classes Just like library files, we use include and require to bring class code into our applications. We can also use autoloading if our classes are predictably named. function __autoload($classname) { if(preg_match('/[a-zA-Z]+Controller$/',$classname)) { include('../controllers/' . $classname . '.php'); return true; } elseif(preg_match('/[a-zA-Z]+Model$/',$classname)) { include('../models/' . $classname . '.php'); return true; } elseif(preg_match('/[a-zA-Z]+View$/',$classname)) { include('../views/' . $classname . '.php'); return true; } } No need to include/require if you have autoloading 10
  • 12. Objects and References Objects are always passed by reference $red_table = new Table(); $red_table->legs = 4; $other_table = $red_table; $other_table->legs = 3; echo $red_table->legs; // output: 3 Objects behave differently from variables • objects are always references, when assigned and when passed around • variables are copied when they are passed into a function • you can pass by reference by using & 11
  • 13. Copying Objects If you actually want to copy an object, you need to use the clone keyword $red_table = new Table(); $red_table->legs = 4; $other_table = clone $red_table; $other_table->legs = 3; echo $red_table->legs; // output: 4 12
  • 15. Inheritance OOP supports inheritance • similar classes can share a parent and override features • improves modularity, avoids duplication • classes can only have one parent (unlike some other languages) • classes can have many children • there can be as many generations of inheritance as we need 14
  • 16. How NOT to Design Class Hierarchies • create one class per database table • instantiate one object of each class • pass all required data in as parameters (or globals!) • never use $this ... note that the title says "NOT" 15
  • 17. Designing Class Hierarchies • identify "things" in your system (users, posts, orders) • what qualities do they share? • where are objects similar? Or different? • in MVC systems, remember that controllers and views are often objects too 16
  • 18. Inheritance Examples class Table { public $legs; public function getLegCount() { return $this->legs; } } class DiningTable extends Table {} $newtable = new DiningTable(); $newtable->legs = 6; echo $newtable->getLegCount(); // 6 17
  • 20. Visibility We can control which parts of a class are available and where: • public: always available, everywhere • private:* only available inside this class • protected: only available inside this class and descendants This applies to both methods and properties * use with caution! Protected is almost always a better choice 19
  • 21. Protected Properties class Table { protected $legs; public function getLegCount() { return $this->legs; } public function setLegCount($legs) { $this->legs = $legs; return true; } } $table = new Table(); $table->legs = 4; // Fatal error: Cannot access protected property Table::$legs in /.../ 20
  • 22. Protected Properties class Table { protected $legs; public function getLegCount() { return $this->legs; } public function setLegCount($legs) { $this->legs = $legs; return true; } } $table = new Table(); $table->setLegCount(4); echo $table->getLegCount(); It is common to use "getters" and "setters" in this way, especially if you are a Java programmer 21
  • 23. Protected Methods Access modifiers for methods work exactly the same way: class Table { protected function getColours() { return array("beech", "birch", "mahogany"); } } class DiningTable extends Table { public function colourChoice() { return parent::getColours(); } } If Table::getColours() were private, DiningTable would think that method was undefined 22
  • 24. Object Keywords • parent: the class this class extends 23
  • 25. Object Keywords • parent: the class this class extends • self: this class, usually used in a static context, instead of $this • WARNING: in extending classes, this resolves to where it was declared • This was fixed in PHP 5.3 by "late static binding" 23
  • 26. Object Keywords • parent: the class this class extends • self: this class, usually used in a static context, instead of $this • WARNING: in extending classes, this resolves to where it was declared • This was fixed in PHP 5.3 by "late static binding" • static: the class in which the code is being used • Just like self but actually works :) 23
  • 28. The instanceOf Operator To check whether an object is of a particular class, use instanceOf $table = new DiningTable(); if($table instanceOf DiningTable) { echo "a dining tablen"; } if($table instanceOf Table) { echo "a tablen"; } InstanceOf will return true if the object: • is of that class • is of a child of that class • implements that interface (more on interfaces later) 25
  • 29. Type Hinting We have type hinting in PHP for complex types. So we can do: function moveFurniture(Table $table) { $table->move(); // imagine something more exciting return true; } PHP will error unless the argument: • is of that class • is of a child of that class • implements that class (more on interfaces later) ... look familiar? 26
  • 30. Comparing Objects • Comparison == • objects must be of the (exact) same class • objects must have identical properties • Strict comparison === • both arguments must refer to the same object 27
  • 31. Magical Mystery Tour (of Magic Methods)
  • 32. Magic Methods • two underscores in method name • allow us to override default object behaviour • really useful for Design Patterns and solving tricky problems 29
  • 33. Constructors • __construct: called when a new object is instantiated • declare any parameters you like • usually we inject dependencies • perform any other setup $blue_table = new BlueTable(); 30
  • 34. Destructors • __destruct: called when the object is destroyed • good time to close resource handles 31
  • 35. Fake Properties When we access a property that doesn’t exist, PHP calls __get() or __set() for us class Table { public function __get($property) { // called if we are reading echo "you asked for $propertyn"; } public function __set($property, $value) { // called if we are writing echo "you tried to set $property to $valuen"; } } $table = new Table(); $table->legs = 5; echo "table has: " . $table->legs . "legsn"; 32
  • 36. Fake Methods PHP calls __call when we call a method that doesn’t exist class Table { public function shift($x, $y) { // the table moves echo "shift table by $x and $yn"; } public function __call($method, $arguments) { // look out for calls to move(), these should be shift() if($method == "move") { return $this->shift($arguments[0], $arguments[1]); } } } $table = new Table(); $table->shift(3,5); // shift table by 3 and 5 $table->move(4,9); // shift table by 4 and 9 There is an equivalent function for static calls, __callStatic() 33
  • 37. Serialising Objects We can control what happens when we serialize and unserialize objects class Table { } $table = new Table(); $table->legs = 4; $table->colour = "red"; echo serialize($table); // O:5:"Table":2:{s:4:"legs";i:4;s:6:"colour";s:3:"red";} 34
  • 38. Serialising Objects • __sleep() to specify which properties to store • __wakeup() to put in place any additional items on unserialize class Table { public function __sleep() { return array("legs"); } } $table = new Table(); $table->legs = 7; $table->colour = "red"; $data = serialize($table); echo $data; // O:5:"Table":1:{s:4:"legs";i:7;} 35
  • 39. Serialising Objects • __sleep() to specify which properties to store • __wakeup() to put in place any additional items on unserialize class Table { public function __wakeup() { $this->colour = "wood"; } } echo $data; $other_table = unserialize($data); print_r($other_table); /* Table Object ( [legs] => 7 [colour] => wood ) */ 36
  • 40. Magic Tricks: clone Control the behaviour of cloning an object by defining __clone() • make it return false to prevent cloning (for a Singleton) • recreate resources that shouldn’t be shared 37
  • 41. Magic Tricks: toString Control what happens when an object cast to a string. E.g. for an exception class TableException extends Exception { public function __toString() { return '** ' . $this->getMessage() . ' **'; } } try { throw new TableException("it wobbles!"); } catch (TableException $e) { echo $e; } // output: ** it wobbles! ** The default output would be exception ’TableException’ with message ’it wobbles!’ in /.../tostring.php:7 Stack trace: 38
  • 44. Exceptions are Objects Exceptions are fabulous They are pretty good use of OOP too! • Exceptions are objects • Exceptions have properties • We can extend exceptions to make our own 40
  • 45. Raising Exceptions In PHP, we can throw any exception, any time. function addTwoNumbers($a, $b) { if(($a == 0) || ($b == 0)) { throw new Exception("Zero is Boring!"); } return $a + $b; } echo addTwoNumbers(3,2); // 5 echo addTwoNumbers(5,0); // error!! Fatal error: Uncaught exception ’Exception’ with message ’Zero is Boring!’ in / Stack trace: #0 /.../exception.php(12): addTwoNumbers(5, 0) #1 {main} thrown in /.../exception.php on line 5 41
  • 46. Catching Exceptions Exceptions are thrown, and should be caught by our code - avoid Fatal Errors! function addTwoNumbers($a, $b) { if(($a == 0) || ($b == 0)) { throw new Exception("Zero is Boring!"); } return $a + $b; } try { echo addTwoNumbers(3,2); echo addTwoNumbers(5,0); } catch (Exception $e) { echo "FAIL!! (" . $e->getMessage() . ")n"; } // there is no "finally" // output: 5FAIL!! (Zero is Boring!) 42
  • 47. Catching Exceptions Exceptions are thrown, and should be caught by our code - avoid Fatal Errors! function addTwoNumbers($a, $b) { if(($a == 0) || ($b == 0)) { throw new Exception("Zero is Boring!"); } return $a + $b; } try { echo addTwoNumbers(3,2); echo addTwoNumbers(5,0); } catch (Exception $e) { echo "FAIL!! (" . $e->getMessage() . ")n"; } // there is no "finally" // output: 5FAIL!! (Zero is Boring!) Did you spot the typehinting?? 43
  • 48. Extending Exceptions Make your own exceptions, and be specific when you catch class DontBeDaftException extends Exception { } function tableColour($colour) { if($colour == "orange" || $colour == "spotty") { throw new DontBeDaftException($colour . 'is not acceptable'); } echo "The table is $colourn"; } try { tableColour("blue"); tableColour("orange"); } catch (DontBeDaftException $e) { echo "Don't be daft! " . $e->getMessage(); } catch (Exception $e) { echo "The sky is falling in! " . $e->getMessage(); } 44
  • 49. Hands up if you’re still alive
  • 51. Abstract Classes Abstract classes are • incomplete • at least partially incomplete 47
  • 52. Abstract Classes Abstract classes are • incomplete • at least partially incomplete • we cannot instantiate them • if a class has an abstract method, the class must be marked abstract too • common in parent classes 47
  • 53. Abstract Examples An abstract class: abstract class Shape { abstract function draw($x, $y); } We can build on it, but must implement any abstract methods class Circle extends Shape { public function draw($x, $y) { // imagine funky geometry stuff echo "circle drawn at $x, $yn"; } } Any non-abstract methods are inherited as normal 48
  • 55. Interfaces • prototypes of class methods • classes "implement" an interface • they must implement all these methods • the object equivalent of a contract PHP does not have multiple inheritance 50
  • 56. Example Interface: Countable This interface is defined in SPL, and it looks like this: Interface Countable { public function count(); } RTFM: http://uk2.php.net/manual/en/class.countable.php 51
  • 57. Implementing Countable Interface We can implement this interface in a class, so long as our class has a count() method class Table implements Countable { public function personArrived() { $this->people++; return true; } public function personLeft() { $this->people--; return true; } public function count() { return $this->people; } } $my_table = new Table(); $my_table->personArrived(); $my_table->personArrived(); echo count($my_table); // 2 52
  • 58. Object Design by Composition This is where interfaces come into their own • class hierarchy is more than inheritance • identify little blocks of functionality • each of these becomes an interface • objects implement as appropriate 53
  • 59. Polymorphism A big word representing a small concept! • we saw typehints and instanceOf • classes identify as themselves, their parents or anything they implement • word roots: • poly: many • morph: body Our object can appear to be more than one thing 54
  • 61. Resources • PHP Manual http://php.net • start here: http://php.net/manual/en/language.oop5.php • Think Vitamin (Disclaimer: my posts!) • http://thinkvitamin.com/code/oop-with-php-finishing-tou • PHP Objects, Patterns and Practice Matt Zandstra (book) 56
  • 62. Further Reading Knwoing OOP means you can go on to learn/use: • PDO • SPL • Design Patterns 57
  • 64. Image Credits • http://www.flickr.com/photos/amiefedora/3897320577 • http://www.flickr.com/photos/silkroadcollection/4886280049 • http://www.flickr.com/photos/dalbera/5336748810 • http://www.flickr.com/photos/stml/3625386561/ • http://www.flickr.com/photos/mikebaird/1958287914 • http://www.flickr.com/photos/dalbera/5336748810 • http://www.flickr.com/photos/mr_git/1118330301/ • http://www.flickr.com/photos/mafleen/1782135825 59