Thursday, January 10, 2013

Overriding Methods

Just because a child class inherits from a parent doesn't mean that the child class necessarily needs to use the parent class 's implementation of a function.For example, if you were designing an application that needed to calculate the area of different geometric shapes, you might have classes called Rectangle and Triangle .Both of these shapes are polygons,and as such these classes will inherit from a parent class called Polygon.

In this example , we will create two classes-Rectangle and Square .A square is a special kind of rectangle.Anything you can do with a rectangle you can do with a square ;however,because a rectangle has two different side lengths and a square  has only one, you need to do some things differently.

saved as class.Rectangle.php

<?php
   class Rectangle{
       public $height;
       public $width;
      
       public function _construct($width,$height){
           $this->width=$width;
           $this->height=$height;
       }
       public function getArea(){
           return $this->height*$this->width;
       }
   }
?>





saved as class.Square.php
<?php
  require_once('class.Rectangle.php');
  class Square extends Rectangle{
      public function _construct($size){
          $this->height=$size;
          $this->width=$size;
      }
      public function getArea(){
          return pow($this->height,2);
      }
  }
?>

No comments:

Post a Comment