Advertisement
Achilles

Polymorphism php

Jul 16th, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. <?php
  2.  
  3. // class that extends abstract method must define all abstract declared methods
  4.  
  5. /**
  6. * Polymorphism describes a pattern in object oriented programming
  7. * in which classes have different functionality while sharing a common interface.
  8. * refer to http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/
  9. * OR
  10. * page 44 of Object oriented Programming with php : PACKT
  11. */
  12.  
  13.  
  14. abstract class Shape
  15. {
  16. private $_color = "black";
  17. private $_filled = false;
  18.  
  19. public function getColor()
  20. {
  21. return $this->_color;
  22. }
  23.  
  24. public function setColor( $color )
  25. {
  26. $this->_color = $color;
  27. }
  28.  
  29. public function isFilled()
  30. {
  31. return $this->_filled;
  32. }
  33.  
  34. public function fill()
  35. {
  36. $this->_filled = true;
  37. }
  38.  
  39. public function makeHollow()
  40. {
  41. $this->_filled = false;
  42. }
  43.  
  44. abstract public function getArea(); // define this method in any class that extends it
  45.  
  46. } // End of abstact class MyAbstract
  47.  
  48. class Rectangle extends Shape
  49. {
  50. private $_width = 0;
  51. private $_height = 0;
  52.  
  53. public function getWidth()
  54. {
  55. return $this->_width;
  56. }
  57.  
  58. public function getHeight()
  59. {
  60. return $this->_height;
  61. }
  62.  
  63. public function setWidth( $width )
  64. {
  65. $this->_width = $width;
  66. }
  67.  
  68. public function setHeight( $height )
  69. {
  70. $this->_height = $height;
  71. }
  72.  
  73. public function getArea()
  74. {
  75. return $this->_height * $this->_width;
  76. }
  77.  
  78. } // End of class Rectangle , extending Shape
  79.  
  80. echo "<pre>";
  81.  
  82. $r = new Rectangle();
  83.  
  84. $r->setWidth(10);
  85. $r->setHeight(20);
  86.  
  87. echo $r->getWidth() . "<br>" ;
  88. echo $r->getHeight() . "<br>" ;
  89.  
  90. echo $r->getColor() . "<br>";
  91. $r->setColor("Green");
  92. echo $r->getColor() . "<br>";
  93.  
  94. var_dump( $r->isFilled() ) ;
  95.  
  96. $r->fill();
  97.  
  98. var_dump( $r->isFilled() ) ;
  99.  
  100. $r->makeHollow();
  101.  
  102. var_dump( $r->isFilled() ) ;
  103.  
  104. echo"</pre>";
  105. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement