Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Object Oriented Programming with PHP

Object Oriented Programming with PHP

Covers basic object oriented programming concepts like class, object, composition, inheritance ...

Jussi Pohjolainen

August 27, 2015
Tweet

More Decks by Jussi Pohjolainen

Other Decks in Technology

Transcript

  1. Intro  to  OO • Object  Oriented  programming  is  a  programming

      paradigm • PHP  is  a  multi-­‐paradigm  programming  language • OO  is  the  most  popular  paradigm  today  and  it's   used  in  most  of  the  languages • Java • C# • C++ • Swift  ...
  2. OO  Benefits • Reusability • Code  can  be  reused •

    Management • Better  management  by  coding  classes  and  objects  that   communicate  with  each  other • Maintanence • When  changing  code,  it  does  not  influence  the  whole   app
  3. Basic  Concept:  Object • In  real  life,  the  world  consists

     of  objects: • cars,  buildings,  trees,  ships,  humans,  flowers.. • Every  object  has  actions  (=methods!)  that  can   incluence  other  objects • jack  drives  ferrari.   • Object  jack  has  a  method  drive  that  influences  some   way  to  object  ferrari. • In  OO,  you  should  implement  the  app  so  that  it   consists  of  objects  that  influence  each  other!
  4. Example  about  an  Object • Datsun  100A  is  an  object

    • Datsun  100A  has  different  actions  or  methods:   • drive • brake • park... • Datsun  100A  has  information  or  attributes:   • color • amount  of  gears • amount  of  doors...
  5. Basic  Concept:  Class • Class  is  a  blueprint  or  template

     of  an  object • Class  describes  the  state  and  behaviour  to  it's   objects. • Object  is  created  from  the  class.
  6. Examples:  Class  to  Object Class Object Car datsun 100a Human

    Jack  Bauer Color red Laptop MacBook  Pro String "some  string" Array {1,2,3,2,4} ... ...
  7. Objects  datsun,  tesla,  škoda • datsun • brand:  "Datsun 100A"

    ,  horsePower:  45,   fuzzy  dices:  true,  color:  {255,0,0} • tesla • brand:  "Tesla Model S",  horsePower:  700,   fuzzy  dices:  false,  color:  {255,0,0} • škoda • brand:  "Škoda Superb Combi",  horsePower 120,  fuzzy  dices:  true,  color:  {255,255,255}
  8. From  Class  to  Object datsun Datsun  100A 1.0 3 red

    true lambo Lamborghini  Diablo 8.0 3 red false Car brand motor amountOfDoors color hasFuzzyDices . .
  9. Person firstname lastname age profession phonenumber eat sleep drinkBeer Person

     – class  to  PHP class Person { public $firstname; public $lastname; public $age; public $profession; public $phonenumber; function eat() { print "Eating"; } function sleep() { print "Sleeping"; } function drinkBeer() { print "Drinking   Beer"; } }
  10. From  Class  to  Object class Person { public $firstname; public

    $lastname; function drinkBeer() { print "Drinking  Beer"; } } $jack = new Person(); $jack-­‐>firstname = "Jack"; $jack-­‐>lastname = "Bauer"; $jack-­‐>drinkBeer();
  11. Creating  Objects  From  the  Class class Car { public $brand;

    public $amountOfGas; function drive() { $this-­‐>amountOfGas-­‐-­‐; } } $ferrari = new Car(); $ferrari-­‐>brand = "Ferrari  California"; $ferrari-­‐>amountOfGas = 100; $ferrari-­‐>drive(); print $ferrari-­‐>amountOfGas;
  12. About  Attributes • Attributes  are  usually  marked  as  private •

    The  reason  for  this  is  that  other  objects  cannot   change  the  values as  they  will • You  don't  for  example  want  that  every  object  in  the   world  can  change  person's  weight  to  500kg...
  13. Cannot  Access  Private class Person { private $name; private $weight;

    } $jack = new Person(); $jack-­‐>name = "Jack  Bauer"; >  php  Person.php Fatal  error:  Cannot  access  private  property  Person::$name  in   /path/to/Person.php   on  line  10
  14. class Person { private $name; private $weight; function setName($name) {

    if(is_string($name) && strlen($name) >= 3) { $this-­‐>name = $name; } } function getName() { return $this-­‐>name; } function setWeight($weight) { if(is_numeric($weight) && $weight > 0 && $weight <= 500) { $this-­‐>weight = $weight; } } function getWeight() { return $this-­‐>weight; } } $jack = new Person(); $jack-­‐>setName("Jack  Bauer"); $jack-­‐>setWeight(80); $jack-­‐>setWeight(-­‐80); $jack-­‐>setWeight("Just  testing"); print $jack-­‐>getWeight(); //  80
  15. Passing  Objects jack = new Person(); $jack-­‐>setName("Jack  Bauer"); $jack-­‐>setWeight(80); $jack-­‐>setWeight(-­‐80);

    $jack-­‐>setWeight("Just  testing"); print $jack-­‐>getWeight(); //  80 $john = $jack; print $john-­‐>getWeight(); //  ?? $jack-­‐>setWeight(90); print $jack-­‐>getWeight(): //  ??
  16. Value  vs  Reference • PHP5  basic  types  are  by  default

     passed  by  value • When  doing  this  on  basic  types,  like  ints: • $a  =  $b;  //  $b  integer  value  is  copied  to  $a • Objects  are  passed  by  reference • When  doing  this  on  objects • $a  =  $b;  //  $b  memory  address  is  copied  to  $a
  17. Constructors • Constructor  is  a init  method that  is  called

     when  an   object  is  created • PHP  5  does  not  provide  default  constructor,  like  in   other  languages • Constructor  method  has  a  special  name  in  PHP • __construct() • Constructor  usually  initializes  class  members,   attributes
  18. Destructor class Person { private $name; function __construct($name) { $this-­‐>name

    = $name; print "Creating  " . $this-­‐>name . "\n"; } function __destruct() { print "Destroying:  " . $this-­‐>name . "\n"; } } $jack = new Person("Jack  Bauer");
  19. Composition • Relationship  between  objects,  where  one  object   owns,

     or  has  the  other  object • Example • Car  has  or  owns  Motor • When  Car  is  build,  it's  motor  is  built  also • When  Car  is  destroyed  it's  motor  is  detroyed • Composition  can  be  one  to  one or  one  to  many
  20. class Motor { function __construct() { print "Motor!\n"; } function

    __destruct() { print "Motor  is  killed\n"; } } class Car { private $motor; function __construct() { print "Car!\n"; $this-­‐>motor = new Motor(); } function __destruct() { print "Car  is  killed\n"; } } $c = new Car();
  21. class Professor { function __construct() { print "Professor  was  created!\n";

    } function __destruct() { print "Professor  is  deleted\n"; } } class Department { private $professors; function __construct($professor) { $this-­‐>professors = array(); $this-­‐>professors[] = $professor; print "Deparment  was  created\n"; } function addProfessor($professor) { $this-­‐>professors[] = $professor; } function __destruct() { print "Department  is  deleted\n"; } } $deartment = new Department(); $tina = new Professor(); $jack = new Professor(); $department-­‐>addProfessor($tina); $department-­‐>addProfessor($jack);
  22. PHP  Types • Single  data  type  (Scalar) • boolean •

    integer • float • string • Compound  type • array • object • Special  types • resource • NULL
  23. PHP  Types //  SCALAR  types $integer = 1; $float =

    1.1; $boolean = true; $string = "moi"; //  COMPOUND  types class Person  { } $array = [1,2,3,4]; $object = new Person(); //  SPECIAL  types $resource = //  some  link  to  external  resource $null = NULL;
  24. Introduction  to  Inheritance • Relationship  between  two  more  classes  where

      derived  class  inherites • methods • attributes • ..  of  pre-­‐existing  base  classes • Intended  to  help  reuse  of  existing  code  with  little   or  no  modification
  25. Example class Human   { function eat() { print "Eating

     healthy!"; } } class Programmer  extends Human   { function code() { print "Coding!"; } } $tina = new Programmer(); $tina-­‐>eat(); $tina-­‐>code();
  26. Inheritance  can  be  continous • Derived  class  can  inherit  another

     class,  which   inherits  another  class  and  so  on • Mammal  <-­‐ Human  <-­‐ Worker  <-­‐ Programmer • When  changing  the  base  class  all  the  derived   classes  change  also!
  27. Multiple  Inheritance:   NOT supported  in  PHP5 Driver TaxiDriver licenceID

      :  string yearsOfApproval   :  int areaCode   :  int Conductor accountNumber   :  int What  would  be  a  possible  problem  in  multi-­‐inheritance?
  28. Visibility • public • Visible  in  base  class,  derived  classes

     and  world • protected • Visible  in  base  class  and  derived  classes • private • Visible  only  in  base  class
  29. Public class Human { public function drinkCoffee() { print "Drink

    coffee"; } } class Programmer extends Human { public function codeApps() { $this->drinkCoffee(); print "Code apps"; } } $jack = new Programmer(); $jack->drinkCoffee(); // "Drink Coffee" $jack->codeApps(); // "Drink Coffee Code Apps"
  30. Private class Human { private function drinkCoffee() { print "Drink

    coffee"; } } class Programmer extends Human { public function codeApps() { $this->drinkCoffee(); // Can't access because private print "Code apps"; } } $jack = new Programmer(); $jack->drinkCoffee(); // Can't access because private $jack->codeApps();
  31. Protected class Human { protected function drinkCoffee() { print "Drink

    coffee"; } } class Programmer extends Human { public function codeApps() { $this->drinkCoffee(); // Success, "Drink Coffee" print "Code apps"; } } $jack = new Programmer(); $jack->drinkCoffee(); // Can't access $jack->codeApps(); // "Drink Coffee Code Apps"
  32. Cannot  Access  Private class Person { private $name; private $weight;

    } $jack = new Person(); $jack-­‐>name = "Jack  Bauer"; >  php  Person.php Fatal  error:  Cannot  access  private  property  Person::$name  in   /path/to/Person.php   on  line  10
  33. What  now? class Person { } $jack = new Person();

    $jack-­‐>name = "Jack  Bauer"; >  php  Person.php >
  34. Dynamic  Properties class Person {} $jack = new Person(); //

    In PHP you can add dynamic properties! $jack->name = "Jack Bauer"; print $jack->name;
  35. Dynamic  Properties class Person { private $name = ""; }

    class Programmer extends Person { } // Jack now does not have $name, it does not // know anything about it. $jack = new Programmer(); // We are adding a NEW property to programmer! // This can be very confusing! $jack->name = "Jack Smith"; print $jack->name; // Outputs "Jack Smith"
  36. Example class Person { function eat() { print "Eating  healthy!";

    } } class Programmer  extends Person { function eat() { print "Eating  pizza!"; } } $tina = new Programmer(); $tina-­‐>eat();
  37. parent class Person { public $name; function printInfo() { print

    "name  =  " . $this-­‐>name . "\n"; } } class Programmer  extends Person { public $salary; function printInfo() { parent::printInfo(); print "salary  =  " . $this-­‐>salary . "\n"; } } $tina = new Programmer(); $tina-­‐>name = "Tina"; $tina-­‐>salary = 4000; $tina-­‐>printInfo();
  38. parent and  constructors class Person { private $name; function __construct($name)

    { $this-­‐>name = $name; } function __toString() { return $this-­‐>name . "\n"; } } class Programmer   extends Person { private $salary; function __construct($name, $salary) { parent::__construct($name); $this-­‐>salary = $salary; } function __toString() { return parent::__toString() . $this-­‐>salary . "\n"; } }
  39. Abstract  Class • Abstract  class  is  class  which  you  cannot

     instantiate   (create  objects) • It's  possible  to  inherite  abstract  class  and  create   objects  from  the  inherited  class,  it  it  is  concrete  one • Abstract  class  may  have  abstract  methods  that  do   not  have  implementations • Abstract  methods  must  be  implemented  in  derived   classes
  40. Code abstract class Mammal { abstract function makeSound(); } class

    Elephant extends Mammal { public function makeSound() { print("Pruuut!"); } } // $m = new Mammal(); $e = new Elephant(); $e->makeSound();
  41. abstract class Shape { public $x; public $y; abstract function

    surfaceArea(); } class Circle extends Shape { public $radius; public function surfaceArea() { return pi() * $this->radius * $this->radius; } } class Rectangle extends Shape { public $width; public $height; public function surfaceArea() { return $this->width() * $this->height; } } $c = new Circle(); $c->x = 50; $c->y = 50; $c->radius = 3; print ($c->surfaceArea());
  42. Interface • Interface  is  a  abstract  class  that  holds  only

     abstract   methods • Class  can  implement  several  interfaces • Class  can  inherite  only  one  class
  43. Code interface MovingObject { public function move(); } class Car

    implements MovingObject { public function move() { print "Car is moving"; } } $c = new Car(); $c->move();
  44. Code interface MovingObject { public function move(); } interface RunsOnGasoline

    { public function addMoreGasoline(); public function reduceGasoline(); } class Car implements MovingObject, RunsOnGasoline { public function move() { print "Car is moving"; } public function addMoreGasoline() { ... } public function reduceGasoline() { ... } } class Mammal {} class Human extends Mammal implements MovingObject { public function move() { print "Human is moving"; } }
  45. Type  Declarations • Force  function  parameters  to  be  certain  type

    • If  not,  error  is  generated • Valid  types  in  PHP5 • class/interface,  self,  array,  callable • Valid  types  in  PHP7 • In  addition  to  the  previous,  bool,  float,  int  string
  46. Type  Declaration class Human { public function move() { print

    "Human is moving"; } } doSomething(new Human()); function doSomething(Human $a) { $a->move(); } Now  you  can  pass  only   Human  objects!
  47. class Mammal { public $name; public function move() { print

    "$this->name is moving\n"; } } class Dog extends Mammal { public function bark() { print "$this->name is barking\n"; } } class Human extends Mammal { public function createArt() { print "$this->name is creating art\n"; } } $human = new Human(); $human->name = "Jack"; $dog = new Dog(); $dog->name = "Spot"; doSomething($human); doSomething($dog); function doSomething(Mammal $a) { $a->move(); } You  can  pass  Mammals,   Dogs  and  Humans!
  48. abstract class Mammal { public $name; abstract public function makeSound();

    } class Dog extends Mammal { public function makeSound() { print "$this->name is barking\n"; } } class Human extends Mammal { public function makeSound() { print "$this->name is creating älämölö\n"; } } $human = new Human(); $human->name = "Jack"; $dog = new Dog(); $dog->name = "Spot"; doSomething($human); doSomething($dog); function doSomething(Mammal $a) { $a->makeSound(); } Now  every  Mammal   has  makeSound   method  so  this  will   always  work!
  49. interface MovingObject { public function move(); } class Car implements

    MovingObject { public function move() { print "Car is moving"; } } abstract class Mammal { public $name; abstract public function makeSound(); } class Human extends Mammal implements MovingObject { public function makeSound() { print "$this->name is creating älämölö\n"; } public function move() { print "$this->name is moving"; } } $human = new Human(); $human->name = "Jack"; $car = new Car(); doSomething($human); doSomething($car); function doSomething(MovingObject $a) { $a->move(); } Now  you  can  pass   objects  that   implements   MovingObject!
  50. interface MovingObject { public function move(); } class Car implements

    MovingObject { public function move() { print "Car is moving"; } } class Robot implements MovingObject { public function move() { print "Robot is moving"; } } class RemoteControl { private $target; public function __construct(MovingObject $target) { $this->target = $target; } public function keyArrowRight() { $this->target->move(); } } $r = new RemoteControl(new Car()); $r->keyArrowRight();