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

What's hot

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
Ramasubbu .P
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
Vibrant Technologies & Computers
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
David Stockton
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
Chhom Karath
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
Denis Ristic
 
Oops in php
Oops in phpOops in php
Oops in php
sanjay joshi
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
 
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
Vibrant Technologies & Computers
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
Nyros Technologies
 
Introduction to PHP OOP
Introduction to PHP OOPIntroduction to PHP OOP
Introduction to PHP OOP
fakhrul hasan
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
Ahmed Swilam
 
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
Sujith Kumar
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
Only oop
Only oopOnly oop
Only oop
anitarooge
 

What's hot (20)

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented 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
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
Oops in php
Oops in phpOops in php
Oops 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
 
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
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
Introduction to PHP OOP
Introduction to PHP OOPIntroduction to PHP OOP
Introduction to PHP OOP
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
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
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Only oop
Only oopOnly oop
Only oop
 
Cfphp Zce 01 Basics
Cfphp Zce 01 BasicsCfphp Zce 01 Basics
Cfphp Zce 01 Basics
 

Similar to Object Oriented PHP5

Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
Alena 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 PHP
Alena Holligan
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
Alena Holligan
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
machuga
 
PHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxPHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptx
Atikur Rahman
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
Alena Holligan
 
PHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptxPHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptx
Atikur Rahman
 
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
Dhivyaa C.R
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
Rohan Sharma
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
sanjay joshi
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and Github
Jo Erik San Jose
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
Alena Holligan
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comtutorialsruby
 
Oop in php tutorial
Oop in php tutorialOop in php tutorial
Oop in php tutorial
Gua Syed Al Yahya
 
Oop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.comOop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.comayandoesnotemail
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comtutorialsruby
 

Similar to Object Oriented PHP5 (20)

Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in 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
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
PHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxPHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptx
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
PHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptxPHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.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
 
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
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and Github
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.com
 
Oop in php tutorial
Oop in php tutorialOop in php tutorial
Oop in php tutorial
 
Oop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.comOop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.com
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.com
 

More from Jason Austin

Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to Elasticsearch
Jason Austin
 
Service Oriented Architecture
Service Oriented ArchitectureService Oriented Architecture
Service Oriented Architecture
Jason Austin
 
How Beer Made Me A Better Developer
How Beer Made Me A Better DeveloperHow Beer Made Me A Better Developer
How Beer Made Me A Better Developer
Jason Austin
 
Securing Your API
Securing Your APISecuring Your API
Securing Your API
Jason Austin
 
Preparing Traditional Media for a Mobile World
Preparing Traditional Media for a Mobile WorldPreparing Traditional Media for a Mobile World
Preparing Traditional Media for a Mobile World
Jason Austin
 
UNC CAUSE - Going Mobile On Campus
UNC CAUSE - Going Mobile On CampusUNC CAUSE - Going Mobile On Campus
UNC CAUSE - Going Mobile On Campus
Jason Austin
 
RSS Like A Ninja
RSS Like A NinjaRSS Like A Ninja
RSS Like A Ninja
Jason Austin
 
Lean mean php machine
Lean mean php machineLean mean php machine
Lean mean php machine
Jason Austin
 
Web Hosting Pilot - NC State University
Web Hosting Pilot - NC State UniversityWeb Hosting Pilot - NC State University
Web Hosting Pilot - NC State University
Jason Austin
 
Tweeting For NC State University
Tweeting For NC State UniversityTweeting For NC State University
Tweeting For NC State University
Jason Austin
 
Pathways Project on NCSU Web Dev
Pathways Project on NCSU Web DevPathways Project on NCSU Web Dev
Pathways Project on NCSU Web Dev
Jason Austin
 

More from Jason Austin (12)

Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to Elasticsearch
 
Service Oriented Architecture
Service Oriented ArchitectureService Oriented Architecture
Service Oriented Architecture
 
Design patterns
Design patternsDesign patterns
Design patterns
 
How Beer Made Me A Better Developer
How Beer Made Me A Better DeveloperHow Beer Made Me A Better Developer
How Beer Made Me A Better Developer
 
Securing Your API
Securing Your APISecuring Your API
Securing Your API
 
Preparing Traditional Media for a Mobile World
Preparing Traditional Media for a Mobile WorldPreparing Traditional Media for a Mobile World
Preparing Traditional Media for a Mobile World
 
UNC CAUSE - Going Mobile On Campus
UNC CAUSE - Going Mobile On CampusUNC CAUSE - Going Mobile On Campus
UNC CAUSE - Going Mobile On Campus
 
RSS Like A Ninja
RSS Like A NinjaRSS Like A Ninja
RSS Like A Ninja
 
Lean mean php machine
Lean mean php machineLean mean php machine
Lean mean php machine
 
Web Hosting Pilot - NC State University
Web Hosting Pilot - NC State UniversityWeb Hosting Pilot - NC State University
Web Hosting Pilot - NC State University
 
Tweeting For NC State University
Tweeting For NC State UniversityTweeting For NC State University
Tweeting For NC State University
 
Pathways Project on NCSU Web Dev
Pathways Project on NCSU Web DevPathways Project on NCSU Web Dev
Pathways Project on NCSU Web Dev
 

Recently uploaded

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 

Recently uploaded (20)

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 

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

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. Describe a little about how exactly a class becomes an object and how that works with respect to interacting with an object in memory and not the class specifically\n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. First one is false, second one is true\n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. Talk about difference from PHP4\n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n