SHOW:
|
|
- or go back to the newest paste.
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 | * http://www.easylearntutorial.com/2012/11/advanced-php-tutorial-what-is-polymorphism.html#.UeUwgkAyagZ | |
10 | * OR | |
11 | * page 44 of Object oriented Programming with php : PACKT | |
12 | */ | |
13 | ||
14 | ||
15 | abstract class Shape | |
16 | { | |
17 | private $_color = "black"; | |
18 | private $_filled = false; | |
19 | ||
20 | public function getColor() | |
21 | { | |
22 | return $this->_color; | |
23 | } | |
24 | ||
25 | public function setColor( $color ) | |
26 | { | |
27 | $this->_color = $color; | |
28 | } | |
29 | ||
30 | public function isFilled() | |
31 | { | |
32 | return $this->_filled; | |
33 | } | |
34 | ||
35 | public function fill() | |
36 | { | |
37 | $this->_filled = true; | |
38 | } | |
39 | ||
40 | public function makeHollow() | |
41 | { | |
42 | $this->_filled = false; | |
43 | } | |
44 | ||
45 | abstract public function getArea(); // define this method in any class that extends it | |
46 | ||
47 | } // End of abstact class MyAbstract | |
48 | ||
49 | class Rectangle extends Shape | |
50 | { | |
51 | private $_width = 0; | |
52 | private $_height = 0; | |
53 | ||
54 | public function getWidth() | |
55 | { | |
56 | return $this->_width; | |
57 | } | |
58 | ||
59 | public function getHeight() | |
60 | { | |
61 | return $this->_height; | |
62 | } | |
63 | ||
64 | public function setWidth( $width ) | |
65 | { | |
66 | $this->_width = $width; | |
67 | } | |
68 | ||
69 | public function setHeight( $height ) | |
70 | { | |
71 | $this->_height = $height; | |
72 | } | |
73 | ||
74 | public function getArea() | |
75 | { | |
76 | return $this->_height * $this->_width; | |
77 | } | |
78 | ||
79 | } // End of class Rectangle , extending Shape | |
80 | ||
81 | echo "<pre>"; | |
82 | ||
83 | $r = new Rectangle(); | |
84 | ||
85 | $r->setWidth(10); | |
86 | $r->setHeight(20); | |
87 | ||
88 | echo $r->getWidth() . "<br>" ; | |
89 | echo $r->getHeight() . "<br>" ; | |
90 | ||
91 | echo $r->getColor() . "<br>"; | |
92 | $r->setColor("Green"); | |
93 | echo $r->getColor() . "<br>"; | |
94 | ||
95 | var_dump( $r->isFilled() ) ; | |
96 | ||
97 | $r->fill(); | |
98 | ||
99 | var_dump( $r->isFilled() ) ; | |
100 | ||
101 | $r->makeHollow(); | |
102 | ||
103 | var_dump( $r->isFilled() ) ; | |
104 | ||
105 | echo"</pre>"; | |
106 | ?> |