SlideShare a Scribd company logo
OBJECT-ORIENTED PRINCIPLES
       WITH PHP5




     Jason Austin - @jason_austin

     TriPUG Meetup - Jan 18, 2011
Goals


Explain object-oriented concepts

Introduce PHP5’s object oriented interface

Illustrate how object-oriented programming can help you

Help you write better code
What makes good software?

"The function of good software is to make the complex
appear to be simple." - Grady Booch



"Always code as if the guy who ends up maintaining your
code will be a violent psychopath who knows where you
live." - Martin Golding



Good software needs good software engineering
Software engineering != programming




     “Programming is just typing” - Everette Allen
What is software engineering then?




Software engineering is the application of a systematic,
quantifiable, disciplined approach to development.


Programming is simply one phase of development
PHP & Software Engineering


PHP is quick to learn, almost to a fault

Easy to write bad code

  However, PHP provides tools to facilitate the creation of
  solid and organized software

PHP started as a procedural language, but has evolved!
Procedural Code

<?php
     include “config.php”;
     include “display.php”;
     mysql_connect($host, $user, $pass);
     echo “<html>”;
     echo “   <head>”;
     echo “      <title>Page</title>”;
     echo “    </head>”;
     echo “    <body>”;
     printMenu();
     $result = mysql_query(“Select * from news”);
     printContent($result);
     echo “</body></html>”;
?>
What’s Wrong With That!?


Nothing is really wrong with it. But...

    It’s really hard to read and follow

    As the code base grows, maintainability decreases

    New additions often become hacks

    Designers can’t easily design unless they know PHP
How else would I do it?!




Object Oriented Programming FTW!
What is OOP?



Programming paradigm using “objects” and their interactions

Not really popular until 1990’s

Basically the opposite of procedural programming
When would I use this OOP stuff?

 When you...

  find yourself repeating code

  want to group certain functions together

  want to easily share some of your code

  want to have an organized code base

  think you may reuse some of your code later
Why OOP?


code resuse!!!

maintainability

code reuse!!!

readability

code reuse!!!
OOP Techniques

Before we get to the code, a little OOP primer

   Encapsulation

   Modularity

   Inheritance

   Polymorphism
Encapsulation (It’s like a Twinkie!)
Group together data and functionality (bananas and cream)

Hide implementation details (how they get the filling in there)

Provide an explicitly defined
way to interact with the data
(they’re always the same shape)

Hides the creamy center!
Modularity (It’s like this sofa!)

A property of an application that measures the extent to
which the application has been composed of separate parts
(modules)

Easier to have a more
loosely-coupled application

No one part is programatically
bound to another
Inheritance (It’s like Joan & Melissa Rivers)

   A hierarchical way to organize data and functionality

   Children receive functionality and properties of their
   ancestors

   is-a and has-a relationships

   Inherently (hah!) encourages
   code reuse
Polymorphism (It’s like that guy)


Combines all the other techniques

Kind of complicated so we’ll get to
it later
Need to know terms

class - A collection of interrelated functions and variables
that manipulates a single idea or concept.

instantiate - To allocate memory for a class.

object - An instance of a class

method - A function within a class

class member - A method or variable within a class
What does a class look like?
<?php

     // this is a class.   $name and getHeight() are class members

     class Person
     {
         public $name = “Bob McSmithyPants”; // this is a class variable

         public function getHeight() // this is a class method
         {}
     }
?>
How to instantiate a class

<?php
    $p = new Person(); // at this point $p is a new Person object
?>



 Now anyone can use the Person object (call its methods,
 change its variables, etc.)
Protecting Your Stuff


What if you want to keep methods and data from being changed?
Scoping

Foundation of OOP

Important for exposing functionality and data to users

Protect data and method integrity
Scopes


public

private

protected
Public
Anyone (the class itself or any instantiation of that class) can have access to the
method or property

If not specified, a method or property is declared public by default
Public Example
<?php

     class Person
     {
         public function getName()
         {
             return “Bob McSmithyPants”;
         }
     }
?>




<?php

     $p = new Person();
     echo $p->getName();
?>
Private
Only the class itself has access to the method or property
Private Example
<?php

     class Person
     {
         public function firstName()
         {
             return “Bob”;
         }

         private function lastName()
         {
             return “McSmithyPants”;
         }
     }
?>



<?php
    $p = new Person();
    echo $p->firstName(); // this will work
    echo $p->lastName(); // this does not work
?>
Protected
Only the class itself or a class that extends this class can
have access to the method or property
Protected Example
<?php

     class Person
     {
         protected function getName()
         {
             return “Bob McSmithyPants”;
         }
     }

     class Bob extends Person
     {
         public function whatIsMyName()
         {
             return $this->getName();
         }
     }
?>

<?php
    $p = new Person();
    echo $p->getName(); // this won’t work

     $b = new Bob();
     echo $b->whatIsMyName();   // this will work
?>
What was with that $this stuff?


You can access the protected data and methods with “object
accessors”

These allow you to keep the bad guys out, but still let the good
guys in.
Object Accessors

Ways to access the data and methods from within objects

 $this

 self

 parent
$this
    variable

    refers to the current instantiation
<?php

class Person
{
    public $name = ‘bob’;

    public function getName()
    {
        return $this->name;
    }
}

$p = new Person();
echo $p->getName();

// will print bob
?>
self
    keyword that refers to the class itself regardless of
    instantiation status

    not a variable
<?php

class Person
{
    public static $name = ‘bob’;

     public function getName()
     {
         return self::$name;
     }
}

$p = new Person();
echo $p->getName();

// will print bob
?>
parent
<?php

class Person                                    keyword that refers to the parent class
{
    public $name = ‘bob’;
                                                most often used when overriding
    public function getName()
    {                                           methods
        return $this->name;
    }
}                                               also not a variable!
class Bob extends Person
{                                               What would happen if we used
    public function getName()
    {                                           $this->getName() instead of
    }
        return strtoupper(parent::getName());   parent::getName()?
}

$bob = new Bob();
echo $bob->getName();

// will print BOB
?>
Class constants


Defined with the “const” keyword

Always static

Not declared or used with $

Must be a constant expression, not a variable, class member,
result of a mathematical expression or a function call

Must start with a letter
Constant Example

<?php

class DanielFaraday
{
    const MY_CONSTANT = 'Desmond';

     public static function getMyConstant()
     {
         return self::MY_CONSTANT;
     }
}

echo DanielFaraday::MY_CONSTANT;

echo DanielFaraday::getMyConstant();

$crazyTimeTravelDude = new DanielFaraday();
echo $crazyTimeTravelDude->getMyConstant();

?>
Class and Method Properties

Final and Static

Classes and methods can be declared either final, static, or
both!
Important Note!

Class member scopes (public, private, and protected) and
the class and method properties (final and static) are not
mutually exclusive!
Final

Properties or methods declared final cannot be overridden by a subclass
Final Example
<?php

     class Person
     {
         public final function getName()
         {
             return “Steve Dave”;
         }
     }

     class Bob extends Person
     {
         public function getName()
         {
             return “Bob McSmithyPants”;
         }
     }

     // this will fail when trying to include Bob
?>
Static

A method declared as static can be accessed without
instantiating the class

You cannot use $this within static functions because $this
refers to the current instantiation

Accessed via the scope resolution operator ( :: )

i.e. – About::getVersion();
Static Example
<?php

     class About
     {
         public static function getVersion()
         {
             return “Version 2.0”;
         }
     }
?>



<?php echo About::getVersion(); ?>
Types of Classes

Abstract Class

Interface
Abstract Classes

Never directly instantiated

Any subclass will have the properties and methods of the
abstract class

Useful for grouping generic functionality of subclassed
objects

At least one method must be declared as abstract
Abstract Example
<?php
                                                 <?php
     abstract class Car
     {                                           $honda = new Honda();
         private $_color;                        $honda->setColor(“black”);
                                                 $honda->drive();
         abstract public function drive();
                                                 ?>
         public function setColor($color)
         {
             $this->_color = $color;
         }

         public function getColor()
         {
             return $this->_color;
         }
     }

     class Honda extends Car
     {
         public function drive()
         {
             $color = $this->getColor();
             echo “I’m driving a $color car!”;
         }
     }
?>
Interfaces


Defines which methods are required for implementing an
object

Specifies the abstract intention of a class without providing
any implementation

Like a blueprint or template

A class can simultaneously implement multiple interfaces
Interface Example
<?php
                                            <?php
     interface Car
     {                                           $honda = new Honda();
         public function start();                $honda->start();
         public function drive();                $honda->drive();
         public function stop();                 $honda->stop();
     }                                      ?>

     class Honda implements Car
     {
         public function start()
         {
             echo “Car is started!”;
         }
         public function drive()
         {
             echo “I’m driving!”;
         }
         public function stop()
         {
             echo “The car has stopped!”;
         }
     }
?>
instanceof

 Operator to check if one class is an instance of another class
<?php
                                                <?php
     class Car
                                                     class Car
     {}
                                                     {}
     class Honda extends Car
                                                     class Honda extends Car
     {}
                                                     {}
     $car = new Car();                OR             $car = new Honda();
     $honda = new Honda();
                                                     if ($car instanceof Car) {
     if ($car instanceof $honda) {
                                                         echo “true”;
         echo “true”;
                                                     } else {
     } else {
                                                         echo “false”;
         echo “false”;
                                                     }
     }
                                                ?>
?>


                             What will get printed?
Type Hinting

PHP is not strongly typed (i.e. - variables can be
pretty much anything anytime)

In PHP4 you have to do a lot of checking
to find out if a parameter is the correct type

Type Hinting helps make this more efficient
Type Hinting Example
<?php
    // this can be made better with type hinting!
    public function promoteToManager($bob)
    {
        if (!is_a($bob, “Person”)) {
            throw new Exception(“$bob is not a Person!”);
        }
        // do stuff with $bob
    }
?>

... becomes ...
<?php
    // this is better!
    public function promoteToManager(Person $bob)
    {
        // do stuff with $bob
    }
?>
A Few More Terms


serialize - Converting an object to a binary form (i.e. -
writing an object to a file)

unserialize - The opposite of serialize. To convert the
stored binary representation of an object back into the
object.

reference - An pointer to an object’s location in memory
rather than the actual object
Magic Methods

Methods provided by PHP5 automagically (called by PHP on certain events)

Always begin with __ (two underscores)

Declared public by default but can be overridden
Magic Methods

__construct()            __sleep()

__destruct()             __wakeup()

__get()                  __isset()

__set()                  __unset()

__call()                 __autoload()

__toString()             __clone()
__construct() & __destruct()


__construct() runs when a new object is instantiated.


Suitable for any initialization that the object may need before
it’s used.


__destruct() runs when all references to an object are no
longer needed or when the object is explicitly destroyed.
__get()

       __get() is called when trying to access an undeclared
       property
<?php
class Car
{

     protected $_data = array(
         ‘door’ => 4,
         ‘type’ => ‘Jeep’,
         ‘vin’ => ‘2948ABJDKZLE’
     );

     public function __get($varName)
     {
         return $this->_data[$varName];
     }
}

$car = new Car();
echo $car->vin; // will print out 2948ABJDKZLE

?>
__set()
       __set() is called when trying to assign an undeclared
       property

<?php
class Car
{

     protected $_data = array(
         ‘door’ => 4,
         ‘type’ => ‘Jeep’,
         ‘vin’ => ‘2948ABJDKZLE’
     );

     public function __set($varName, $value)
     {
         $this->_data[$varName] = $value;
     }
}

$car = new Car();
$car->vin = ‘ABC’;
echo $car->vin; // will print out ABC

?>
__isset()
       Used to check whether or not a data member has been declared
<?php
class Car
{

    protected $_data = array(
        ‘door’ => 4,
        ‘type’ => ‘Jeep’,
        ‘vin’ => ‘2948ABJDKZLE’
    );

    public function __isset($varName)
    {
        return isset($this->_data[$varName]);
    }
}

$car = new Car();

if (isset($car->color)) {
    echo “color is set!”;
} else {
    echo “color isn’t set!”;
}
// will print color isn’t set
?>
__unset()
        Removes a data member from a class
<?php
class Car
{

    protected $_data = array(
        ‘door’ => 4,
        ‘type’ => ‘Jeep’,
        ‘vin’ => ‘2948ABJDKZLE’
    );

    public function __unset($varName)
    {
        return unset($this->_data[$varName]);
    }
}

$car = new Car();
unset($car->vin);

if (isset($car->vin)) {
    echo “vin is set!”;
} else {
   echo “vin isn’t set!”;
}
// will print vin isn’t set
?>
__call()

__call() is executed when trying to access a method that
doesn’t exist

This allows you to handle unknown functions however you’d
like.
_call() Example
<?php
class Sample
{

     public function __call($func, $arguments)
     {
         echo "Error accessing undefined Method<br />";
         echo "Method Called: " . $func . "<br />";
         echo "Argument passed to the Method: ";
         print_r($arguments);
     }
}

$sample = new Sample();
echo $sample->doSomeStuff("Test");

?>
__toString()

Returns the string representation of a class

Is automatically called whenever trying to print or echo a
class.

Useful for defining exactly what you want an object to look
like as a string

Can also be used to prevent people from printing the class
without throwing an exception
__toString() Example
<?php
    class SqlQuery
    {
        protected $_table;
        protected $_where;
        protected $_orderBy;
        protected $_limit;

         public function __construct($table, $where, $orderBy, $limit)
         {
             $this->_table = $table;
             $this->_where = $where;
             $this->_orderBy = $orderBy;
             $this->_limit = $limit;
         }

         public function __toString()
         {
             $query = “SELECT * “
                    . “FROM $this->_table “
                    . “WHERE $this->_where “
                    . “ORDER BY $this->_orderBy “
                    . “LIMIT $this->_limit”;

             return $query;
         }
     }

$test = new SqlQuery('tbl_users', “userType = ‘admin’”, ‘name’, 10);
echo $test;

?>
__sleep()

Called while serializing an object

__sleep() lets you define how you want the object to be
stored

Also allows you to do any clean up you want before
serialization

Used in conjunction with __wakeup()
__wakeup()


The opposite of __sleep() basically

Called when an object is being unserialized

Allows you to restore the class data to its normal form
__clone()


In php setting one object to another
does not copy the original object;
only a reference to the original is
made

To actually get a second copy of the
object, you must use the __clone
method
__clone() example

<?php
    class Animal
    {
        public $color;

        public function setColor($color)
        {
            $this->color = $color;
        }

        public function __clone()
        {
            echo "<br />Cloning animal...";
        }
    }

$tiger = new Animal();
$tiger->color = "Orange";

$unicorn = clone $tiger;
$unicorn->color = "white";

echo "<br /> A tiger is " . $tiger->color;
echo "<br /> A unicorn is " . $unicorn->color;
?>
__autoload()
Called when you try to load a class in a file that was not
already included

Allows you to do new myClass() without having to include
myClass.php first.
_autoload() example
<?php

     class Account
     {

         public function __autoload($classname)
         {
             require_once $classname . ‘.php’; //$classname will be Profile
         }

         public function __construct()
         {
             $profile = new Profile();
         }
     }
?>
A little example

You can use all this stuff you just learned about inheritance,
scoping, interfaces, and abstract classes to do some more
complex things!
How Would You Solve This?

I have a bunch of shapes of which I want to find the area

I could get any combination of different shapes

I want to be able to find the area without having to know
the details of the calculation myself.

What OOP techniques could we use to solve this problem?
Polymorphism is the answer!




...What exactly would you say that is?
Polymorphism



The last object-oriented technique!

Combination of the other techniques

Allowing values of different types to be handled by a uniform
interface
Polymorphism Example!

Polymorphism allows a set of heterogeneous elements to be
treated identically.

Achieved through inheritance
Polymorphism

<?php

     interface HasArea
     {
         public function area();
     }
?>
Polymorphism

<?php

     abstract class Shape
     {
         private $_color;

         public function __construct($color)
         {
             $this->_color = $color;
         }

         public function getColor()
         {
             return $this->_color;
         }
     }
?>
Polymorphism
<?php

     class Rectangle extends Shape implements HasArea
     {
         private $_w; // width
         private $_h; // height

         public function __construct($color, $w, $h)
         {
             parent::__construct($color);
             $this->_w = $w;
             $this->_h = $h;
         }

         public function area()
         {
             return ($this->_w * $this->_h);
         }
     }
?>
Polymorphism

<?php

     class Circle extends Shape implements HasArea
     {
         private $_r; // radius

         public function __construct($color, $r)
         {
             parent::__construct($color);
             $this->_r = $r;
         }

         public function area()
         {
             return (3.14 * pow($this->_r, 2));
         }
     }
?>
Polymorphism
<?php

    // this function will only take a shape that implements HasArea
    function getArea(HasArea $shape)
    {
        return $shape->area();
    }

    $shapes = array(
                  'rectangle' => new Rectangle("red", 2, 3),
                  'circle' => new Circle("orange", 4)
              );

    foreach ($shapes as $shapeName => $shape) {
        $area = getArea($shape);
        echo $shapeName . " has an area of " . $area . "<br />";
    }

// will print:
// rectangle has an area of 6
// circle has an area of 50.24
?>
QUESTIONS?


      Jason Austin

    @jason_austin

  jfaustin@gmail.com

http://jasonawesome.com

More Related Content

PDF
Object Oriented Programming with PHP 5 - More OOP
PPT
Php Oop
PDF
A Gentle Introduction To Object Oriented Php
PDF
Object Oriented Programming in PHP
PDF
OOP in PHP
PPT
Oops in PHP
PPTX
Oop in-php
Object Oriented Programming with PHP 5 - More OOP
Php Oop
A Gentle Introduction To Object Oriented Php
Object Oriented Programming in PHP
OOP in PHP
Oops in PHP
Oop in-php

What's hot (20)

PPT
Class 7 - PHP Object Oriented Programming
PPT
Class and Objects in PHP
PPT
PHP- Introduction to Object Oriented PHP
PPTX
Object oreinted php | OOPs
PDF
Intermediate OOP in PHP
PPTX
Ch8(oop)
PDF
09 Object Oriented Programming in PHP #burningkeyboards
PPTX
Oops in php
PPTX
Object oriented programming in php 5
PPT
PHP - Introduction to Object Oriented Programming with PHP
PPT
Oops in PHP By Nyros Developer
PPTX
Introduction to PHP OOP
PPT
Oops concepts in php
PPT
Introduction to OOP with PHP
PPT
Class 2 - Introduction to PHP
PPTX
Basics of Object Oriented Programming in Python
PPT
Synapseindia object oriented programming in php
PPTX
Only oop
PDF
Cfphp Zce 01 Basics
Class 7 - PHP Object Oriented Programming
Class and Objects in PHP
PHP- Introduction to Object Oriented PHP
Object oreinted php | OOPs
Intermediate OOP in PHP
Ch8(oop)
09 Object Oriented Programming in PHP #burningkeyboards
Oops in php
Object oriented programming in php 5
PHP - Introduction to Object Oriented Programming with PHP
Oops in PHP By Nyros Developer
Introduction to PHP OOP
Oops concepts in php
Introduction to OOP with PHP
Class 2 - Introduction to PHP
Basics of Object Oriented Programming in Python
Synapseindia object oriented programming in php
Only oop
Cfphp Zce 01 Basics
Ad

Similar to Object Oriented PHP5 (20)

PDF
Object Oriented Programming in PHP
PPT
Advanced php
PDF
OOP in PHP
ODP
(An Extended) Beginners Guide to Object Orientation in PHP
PDF
Demystifying Object-Oriented Programming #phpbnl18
PPTX
Lecture-10_PHP-OOP.pptx
PPTX
Php oop (1)
PPTX
PPTX
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
PPTX
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT III (8).pptx
PPTX
UNIT III (8).pptx
DOCX
Oops concept in php
PDF
Demystifying Object-Oriented Programming - PHP[tek] 2017
PDF
Object_oriented_programming_OOP_with_PHP.pdf
PPTX
Object Oriented Programming Basics with PHP
PPTX
Lecture 17 - PHP-Object-Orientation.pptx
PDF
Demystifying Object-Oriented Programming - PHP UK Conference 2017
PPTX
Object oriented programming in php
PPTX
Introduction to PHP and MySql basics.pptx
Object Oriented Programming in PHP
Advanced php
OOP in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
Demystifying Object-Oriented Programming #phpbnl18
Lecture-10_PHP-OOP.pptx
Php oop (1)
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT III (8).pptx
UNIT III (8).pptx
Oops concept in php
Demystifying Object-Oriented Programming - PHP[tek] 2017
Object_oriented_programming_OOP_with_PHP.pdf
Object Oriented Programming Basics with PHP
Lecture 17 - PHP-Object-Orientation.pptx
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Object oriented programming in php
Introduction to PHP and MySql basics.pptx
Ad

More from Jason Austin (12)

PDF
Introduction to Elasticsearch
PDF
Service Oriented Architecture
PDF
Design patterns
PPT
How Beer Made Me A Better Developer
PDF
Securing Your API
ZIP
Preparing Traditional Media for a Mobile World
PDF
UNC CAUSE - Going Mobile On Campus
PDF
RSS Like A Ninja
PDF
Lean mean php machine
PDF
Web Hosting Pilot - NC State University
PDF
Tweeting For NC State University
PDF
Pathways Project on NCSU Web Dev
Introduction to Elasticsearch
Service Oriented Architecture
Design patterns
How Beer Made Me A Better Developer
Securing Your API
Preparing Traditional Media for a Mobile World
UNC CAUSE - Going Mobile On Campus
RSS Like A Ninja
Lean mean php machine
Web Hosting Pilot - NC State University
Tweeting For NC State University
Pathways Project on NCSU Web Dev

Recently uploaded (20)

PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
Teaching material agriculture food technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Electronic commerce courselecture one. Pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
CIFDAQ's Market Insight: SEC Turns Pro Crypto
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Machine learning based COVID-19 study performance prediction
Reach Out and Touch Someone: Haptics and Empathic Computing
Building Integrated photovoltaic BIPV_UPV.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The AUB Centre for AI in Media Proposal.docx
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25 Week I
“AI and Expert System Decision Support & Business Intelligence Systems”
Spectral efficient network and resource selection model in 5G networks
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology
Understanding_Digital_Forensics_Presentation.pptx
Electronic commerce courselecture one. Pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm

Object Oriented PHP5

  • 1. OBJECT-ORIENTED PRINCIPLES WITH PHP5 Jason Austin - @jason_austin TriPUG Meetup - Jan 18, 2011
  • 2. Goals Explain object-oriented concepts Introduce PHP5’s object oriented interface Illustrate how object-oriented programming can help you Help you write better code
  • 3. What makes good software? "The function of good software is to make the complex appear to be simple." - Grady Booch "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." - Martin Golding Good software needs good software engineering
  • 4. Software engineering != programming “Programming is just typing” - Everette Allen
  • 5. What is software engineering then? Software engineering is the application of a systematic, quantifiable, disciplined approach to development. Programming is simply one phase of development
  • 6. PHP & Software Engineering PHP is quick to learn, almost to a fault Easy to write bad code However, PHP provides tools to facilitate the creation of solid and organized software PHP started as a procedural language, but has evolved!
  • 7. Procedural Code <?php include “config.php”; include “display.php”; mysql_connect($host, $user, $pass); echo “<html>”; echo “ <head>”; echo “ <title>Page</title>”; echo “ </head>”; echo “ <body>”; printMenu(); $result = mysql_query(“Select * from news”); printContent($result); echo “</body></html>”; ?>
  • 8. What’s Wrong With That!? Nothing is really wrong with it. But... It’s really hard to read and follow As the code base grows, maintainability decreases New additions often become hacks Designers can’t easily design unless they know PHP
  • 9. How else would I do it?! Object Oriented Programming FTW!
  • 10. What is OOP? Programming paradigm using “objects” and their interactions Not really popular until 1990’s Basically the opposite of procedural programming
  • 11. When would I use this OOP stuff? When you... find yourself repeating code want to group certain functions together want to easily share some of your code want to have an organized code base think you may reuse some of your code later
  • 12. Why OOP? code resuse!!! maintainability code reuse!!! readability code reuse!!!
  • 13. OOP Techniques Before we get to the code, a little OOP primer Encapsulation Modularity Inheritance Polymorphism
  • 14. Encapsulation (It’s like a Twinkie!) Group together data and functionality (bananas and cream) Hide implementation details (how they get the filling in there) Provide an explicitly defined way to interact with the data (they’re always the same shape) Hides the creamy center!
  • 15. Modularity (It’s like this sofa!) A property of an application that measures the extent to which the application has been composed of separate parts (modules) Easier to have a more loosely-coupled application No one part is programatically bound to another
  • 16. Inheritance (It’s like Joan & Melissa Rivers) A hierarchical way to organize data and functionality Children receive functionality and properties of their ancestors is-a and has-a relationships Inherently (hah!) encourages code reuse
  • 17. Polymorphism (It’s like that guy) Combines all the other techniques Kind of complicated so we’ll get to it later
  • 18. Need to know terms class - A collection of interrelated functions and variables that manipulates a single idea or concept. instantiate - To allocate memory for a class. object - An instance of a class method - A function within a class class member - A method or variable within a class
  • 19. What does a class look like? <?php // this is a class. $name and getHeight() are class members class Person { public $name = “Bob McSmithyPants”; // this is a class variable public function getHeight() // this is a class method {} } ?>
  • 20. How to instantiate a class <?php $p = new Person(); // at this point $p is a new Person object ?> Now anyone can use the Person object (call its methods, change its variables, etc.)
  • 21. Protecting Your Stuff What if you want to keep methods and data from being changed?
  • 22. Scoping Foundation of OOP Important for exposing functionality and data to users Protect data and method integrity
  • 24. Public Anyone (the class itself or any instantiation of that class) can have access to the method or property If not specified, a method or property is declared public by default
  • 25. Public Example <?php class Person { public function getName() { return “Bob McSmithyPants”; } } ?> <?php $p = new Person(); echo $p->getName(); ?>
  • 26. Private Only the class itself has access to the method or property
  • 27. Private Example <?php class Person { public function firstName() { return “Bob”; } private function lastName() { return “McSmithyPants”; } } ?> <?php $p = new Person(); echo $p->firstName(); // this will work echo $p->lastName(); // this does not work ?>
  • 28. Protected Only the class itself or a class that extends this class can have access to the method or property
  • 29. Protected Example <?php class Person { protected function getName() { return “Bob McSmithyPants”; } } class Bob extends Person { public function whatIsMyName() { return $this->getName(); } } ?> <?php $p = new Person(); echo $p->getName(); // this won’t work $b = new Bob(); echo $b->whatIsMyName(); // this will work ?>
  • 30. What was with that $this stuff? You can access the protected data and methods with “object accessors” These allow you to keep the bad guys out, but still let the good guys in.
  • 31. Object Accessors Ways to access the data and methods from within objects $this self parent
  • 32. $this variable refers to the current instantiation <?php class Person { public $name = ‘bob’; public function getName() { return $this->name; } } $p = new Person(); echo $p->getName(); // will print bob ?>
  • 33. self keyword that refers to the class itself regardless of instantiation status not a variable <?php class Person { public static $name = ‘bob’; public function getName() { return self::$name; } } $p = new Person(); echo $p->getName(); // will print bob ?>
  • 34. parent <?php class Person keyword that refers to the parent class { public $name = ‘bob’; most often used when overriding public function getName() { methods return $this->name; } } also not a variable! class Bob extends Person { What would happen if we used public function getName() { $this->getName() instead of } return strtoupper(parent::getName()); parent::getName()? } $bob = new Bob(); echo $bob->getName(); // will print BOB ?>
  • 35. Class constants Defined with the “const” keyword Always static Not declared or used with $ Must be a constant expression, not a variable, class member, result of a mathematical expression or a function call Must start with a letter
  • 36. Constant Example <?php class DanielFaraday { const MY_CONSTANT = 'Desmond'; public static function getMyConstant() { return self::MY_CONSTANT; } } echo DanielFaraday::MY_CONSTANT; echo DanielFaraday::getMyConstant(); $crazyTimeTravelDude = new DanielFaraday(); echo $crazyTimeTravelDude->getMyConstant(); ?>
  • 37. Class and Method Properties Final and Static Classes and methods can be declared either final, static, or both!
  • 38. Important Note! Class member scopes (public, private, and protected) and the class and method properties (final and static) are not mutually exclusive!
  • 39. Final Properties or methods declared final cannot be overridden by a subclass
  • 40. Final Example <?php class Person { public final function getName() { return “Steve Dave”; } } class Bob extends Person { public function getName() { return “Bob McSmithyPants”; } } // this will fail when trying to include Bob ?>
  • 41. Static A method declared as static can be accessed without instantiating the class You cannot use $this within static functions because $this refers to the current instantiation Accessed via the scope resolution operator ( :: ) i.e. – About::getVersion();
  • 42. Static Example <?php class About { public static function getVersion() { return “Version 2.0”; } } ?> <?php echo About::getVersion(); ?>
  • 43. Types of Classes Abstract Class Interface
  • 44. Abstract Classes Never directly instantiated Any subclass will have the properties and methods of the abstract class Useful for grouping generic functionality of subclassed objects At least one method must be declared as abstract
  • 45. Abstract Example <?php <?php abstract class Car { $honda = new Honda(); private $_color; $honda->setColor(“black”); $honda->drive(); abstract public function drive(); ?> public function setColor($color) { $this->_color = $color; } public function getColor() { return $this->_color; } } class Honda extends Car { public function drive() { $color = $this->getColor(); echo “I’m driving a $color car!”; } } ?>
  • 46. Interfaces Defines which methods are required for implementing an object Specifies the abstract intention of a class without providing any implementation Like a blueprint or template A class can simultaneously implement multiple interfaces
  • 47. Interface Example <?php <?php interface Car { $honda = new Honda(); public function start(); $honda->start(); public function drive(); $honda->drive(); public function stop(); $honda->stop(); } ?> class Honda implements Car { public function start() { echo “Car is started!”; } public function drive() { echo “I’m driving!”; } public function stop() { echo “The car has stopped!”; } } ?>
  • 48. instanceof Operator to check if one class is an instance of another class <?php <?php class Car class Car {} {} class Honda extends Car class Honda extends Car {} {} $car = new Car(); OR $car = new Honda(); $honda = new Honda(); if ($car instanceof Car) { if ($car instanceof $honda) { echo “true”; echo “true”; } else { } else { echo “false”; echo “false”; } } ?> ?> What will get printed?
  • 49. Type Hinting PHP is not strongly typed (i.e. - variables can be pretty much anything anytime) In PHP4 you have to do a lot of checking to find out if a parameter is the correct type Type Hinting helps make this more efficient
  • 50. Type Hinting Example <?php // this can be made better with type hinting! public function promoteToManager($bob) { if (!is_a($bob, “Person”)) { throw new Exception(“$bob is not a Person!”); } // do stuff with $bob } ?> ... becomes ... <?php // this is better! public function promoteToManager(Person $bob) { // do stuff with $bob } ?>
  • 51. A Few More Terms serialize - Converting an object to a binary form (i.e. - writing an object to a file) unserialize - The opposite of serialize. To convert the stored binary representation of an object back into the object. reference - An pointer to an object’s location in memory rather than the actual object
  • 52. Magic Methods Methods provided by PHP5 automagically (called by PHP on certain events) Always begin with __ (two underscores) Declared public by default but can be overridden
  • 53. Magic Methods __construct() __sleep() __destruct() __wakeup() __get() __isset() __set() __unset() __call() __autoload() __toString() __clone()
  • 54. __construct() & __destruct() __construct() runs when a new object is instantiated. Suitable for any initialization that the object may need before it’s used. __destruct() runs when all references to an object are no longer needed or when the object is explicitly destroyed.
  • 55. __get() __get() is called when trying to access an undeclared property <?php class Car { protected $_data = array( ‘door’ => 4, ‘type’ => ‘Jeep’, ‘vin’ => ‘2948ABJDKZLE’ ); public function __get($varName) { return $this->_data[$varName]; } } $car = new Car(); echo $car->vin; // will print out 2948ABJDKZLE ?>
  • 56. __set() __set() is called when trying to assign an undeclared property <?php class Car { protected $_data = array( ‘door’ => 4, ‘type’ => ‘Jeep’, ‘vin’ => ‘2948ABJDKZLE’ ); public function __set($varName, $value) { $this->_data[$varName] = $value; } } $car = new Car(); $car->vin = ‘ABC’; echo $car->vin; // will print out ABC ?>
  • 57. __isset() Used to check whether or not a data member has been declared <?php class Car { protected $_data = array( ‘door’ => 4, ‘type’ => ‘Jeep’, ‘vin’ => ‘2948ABJDKZLE’ ); public function __isset($varName) { return isset($this->_data[$varName]); } } $car = new Car(); if (isset($car->color)) { echo “color is set!”; } else { echo “color isn’t set!”; } // will print color isn’t set ?>
  • 58. __unset() Removes a data member from a class <?php class Car { protected $_data = array( ‘door’ => 4, ‘type’ => ‘Jeep’, ‘vin’ => ‘2948ABJDKZLE’ ); public function __unset($varName) { return unset($this->_data[$varName]); } } $car = new Car(); unset($car->vin); if (isset($car->vin)) { echo “vin is set!”; } else { echo “vin isn’t set!”; } // will print vin isn’t set ?>
  • 59. __call() __call() is executed when trying to access a method that doesn’t exist This allows you to handle unknown functions however you’d like.
  • 60. _call() Example <?php class Sample { public function __call($func, $arguments) { echo "Error accessing undefined Method<br />"; echo "Method Called: " . $func . "<br />"; echo "Argument passed to the Method: "; print_r($arguments); } } $sample = new Sample(); echo $sample->doSomeStuff("Test"); ?>
  • 61. __toString() Returns the string representation of a class Is automatically called whenever trying to print or echo a class. Useful for defining exactly what you want an object to look like as a string Can also be used to prevent people from printing the class without throwing an exception
  • 62. __toString() Example <?php class SqlQuery { protected $_table; protected $_where; protected $_orderBy; protected $_limit; public function __construct($table, $where, $orderBy, $limit) { $this->_table = $table; $this->_where = $where; $this->_orderBy = $orderBy; $this->_limit = $limit; } public function __toString() { $query = “SELECT * “ . “FROM $this->_table “ . “WHERE $this->_where “ . “ORDER BY $this->_orderBy “ . “LIMIT $this->_limit”; return $query; } } $test = new SqlQuery('tbl_users', “userType = ‘admin’”, ‘name’, 10); echo $test; ?>
  • 63. __sleep() Called while serializing an object __sleep() lets you define how you want the object to be stored Also allows you to do any clean up you want before serialization Used in conjunction with __wakeup()
  • 64. __wakeup() The opposite of __sleep() basically Called when an object is being unserialized Allows you to restore the class data to its normal form
  • 65. __clone() In php setting one object to another does not copy the original object; only a reference to the original is made To actually get a second copy of the object, you must use the __clone method
  • 66. __clone() example <?php class Animal { public $color; public function setColor($color) { $this->color = $color; } public function __clone() { echo "<br />Cloning animal..."; } } $tiger = new Animal(); $tiger->color = "Orange"; $unicorn = clone $tiger; $unicorn->color = "white"; echo "<br /> A tiger is " . $tiger->color; echo "<br /> A unicorn is " . $unicorn->color; ?>
  • 67. __autoload() Called when you try to load a class in a file that was not already included Allows you to do new myClass() without having to include myClass.php first.
  • 68. _autoload() example <?php class Account { public function __autoload($classname) { require_once $classname . ‘.php’; //$classname will be Profile } public function __construct() { $profile = new Profile(); } } ?>
  • 69. A little example You can use all this stuff you just learned about inheritance, scoping, interfaces, and abstract classes to do some more complex things!
  • 70. How Would You Solve This? I have a bunch of shapes of which I want to find the area I could get any combination of different shapes I want to be able to find the area without having to know the details of the calculation myself. What OOP techniques could we use to solve this problem?
  • 71. Polymorphism is the answer! ...What exactly would you say that is?
  • 72. Polymorphism The last object-oriented technique! Combination of the other techniques Allowing values of different types to be handled by a uniform interface
  • 73. Polymorphism Example! Polymorphism allows a set of heterogeneous elements to be treated identically. Achieved through inheritance
  • 74. Polymorphism <?php interface HasArea { public function area(); } ?>
  • 75. Polymorphism <?php abstract class Shape { private $_color; public function __construct($color) { $this->_color = $color; } public function getColor() { return $this->_color; } } ?>
  • 76. Polymorphism <?php class Rectangle extends Shape implements HasArea { private $_w; // width private $_h; // height public function __construct($color, $w, $h) { parent::__construct($color); $this->_w = $w; $this->_h = $h; } public function area() { return ($this->_w * $this->_h); } } ?>
  • 77. Polymorphism <?php class Circle extends Shape implements HasArea { private $_r; // radius public function __construct($color, $r) { parent::__construct($color); $this->_r = $r; } public function area() { return (3.14 * pow($this->_r, 2)); } } ?>
  • 78. Polymorphism <?php // this function will only take a shape that implements HasArea function getArea(HasArea $shape) { return $shape->area(); } $shapes = array( 'rectangle' => new Rectangle("red", 2, 3), 'circle' => new Circle("orange", 4) ); foreach ($shapes as $shapeName => $shape) { $area = getArea($shape); echo $shapeName . " has an area of " . $area . "<br />"; } // will print: // rectangle has an area of 6 // circle has an area of 50.24 ?>
  • 79. QUESTIONS? Jason Austin @jason_austin jfaustin@gmail.com http://jasonawesome.com

Editor's Notes