SlideShare uma empresa Scribd logo
1 de 79
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,
quantiïŹable, 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...

  ïŹnd 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 ïŹlling in there)

Provide an explicitly deïŹned
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 speciïŹed, 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


DeïŹned 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 ïŹnal, static, or
both!
Important Note!

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

Properties or methods declared ïŹnal 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


DeïŹnes which methods are required for implementing an
object

SpeciïŹes 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 ïŹnd out if a parameter is the correct type

Type Hinting helps make this more efïŹcient
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 ïŹle)

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 deïŹning 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 deïŹne 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 ïŹle that was not
already included

Allows you to do new myClass() without having to include
myClass.php ïŹrst.
_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 ïŹnd the area

I could get any combination of different shapes

I want to be able to ïŹnd 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

Mais conteĂșdo relacionado

Mais procurados

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHPDavid Stockton
 
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 #burningkeyboardsDenis Ristic
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5Sayed 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 PHPVibrant Technologies & Computers
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperNyros Technologies
 
Introduction to PHP OOP
Introduction to PHP OOPIntroduction to PHP OOP
Introduction to PHP OOPfakhrul hasan
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD 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 PHPAhmed 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 PythonSujith Kumar
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindiappsdevelopment
 
Only oop
Only oopOnly oop
Only oopanitarooge
 

Mais procurados (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
 

Semelhante a 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 2016Alena Holligan
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPAlena Holligan
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Alena Holligan
 
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] 2017Alena Holligan
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 
PHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxPHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxAtikur Rahman
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oopAlena Holligan
 
PHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptxPHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptxAtikur 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 CollegeDhivyaa C.R
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHPRohan Sharma
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Phpsanjay joshi
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and GithubJo Erik San Jose
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena 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_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_for_killerphp.com
Oop in php_tutorial_for_killerphp.comOop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.comayandoesnotemail
 

Semelhante a 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
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
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_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
 
Oop in php tutorial
Oop in php tutorialOop in php tutorial
Oop in php tutorial
 

Mais de Jason Austin

Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to ElasticsearchJason Austin
 
Service Oriented Architecture
Service Oriented ArchitectureService Oriented Architecture
Service Oriented ArchitectureJason Austin
 
Design patterns
Design patternsDesign patterns
Design patternsJason 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 DeveloperJason Austin
 
Securing Your API
Securing Your APISecuring Your API
Securing Your APIJason 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 WorldJason Austin
 
UNC CAUSE - Going Mobile On Campus
UNC CAUSE - Going Mobile On CampusUNC CAUSE - Going Mobile On Campus
UNC CAUSE - Going Mobile On CampusJason Austin
 
RSS Like A Ninja
RSS Like A NinjaRSS Like A Ninja
RSS Like A NinjaJason Austin
 
Lean mean php machine
Lean mean php machineLean mean php machine
Lean mean php machineJason Austin
 
Web Hosting Pilot - NC State University
Web Hosting Pilot - NC State UniversityWeb Hosting Pilot - NC State University
Web Hosting Pilot - NC State UniversityJason Austin
 
Tweeting For NC State University
Tweeting For NC State UniversityTweeting For NC State University
Tweeting For NC State UniversityJason Austin
 
Pathways Project on NCSU Web Dev
Pathways Project on NCSU Web DevPathways Project on NCSU Web Dev
Pathways Project on NCSU Web DevJason Austin
 

Mais de 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
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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, quantiïŹable, 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... ïŹnd 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 ïŹlling in there) Provide an explicitly deïŹned 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 speciïŹed, 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 DeïŹned 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 ïŹnal, static, or both!
  • 38. Important Note! Class member scopes (public, private, and protected) and the class and method properties (ïŹnal and static) are not mutually exclusive!
  • 39. Final Properties or methods declared ïŹnal 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 DeïŹnes which methods are required for implementing an object SpeciïŹes 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 ïŹnd out if a parameter is the correct type Type Hinting helps make this more efïŹcient
  • 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 ïŹle) 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 deïŹning 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 deïŹne 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 ïŹle that was not already included Allows you to do new myClass() without having to include myClass.php ïŹrst.
  • 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 ïŹnd the area I could get any combination of different shapes I want to be able to ïŹnd 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

Notas do Editor

  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