[Previous] [Contents] [Next]


Reimplementing Methods from My Base Class


One of the things I would like my new DiscountedProduct class to have is an updated constructor that takes in the discount as a parameter. PHP permits us to do this and even to continue to use the base class's own constructor by using a keyword called parent. This keyword, combined with the scope resolution operator (::), lets us call methods belonging to my base class. The act of creating a "new" version of a member function in an inheriting class is often referred to as overriding a method. The overridden method in the base class is replaced by the new one in the extending class.

<?php
  public DiscountedClass extends Product
  {
    protected $discount_percentage = 0.0;
    // etc.

    // one new parameter for the discount.
    public function __construct
   (
      $in_prodid,
      $in_prodname,
      $in_proddesc,
      $in_price_pu,
      $in_location,
      $in_discount_pct
   )
   {
      parent::__construct($in_prodid,
                          $in_prodname,
                          $in_proddesc,
                          $in_price_pu,
                          $in_location);
      $this->discount_percentage = $in_discount_pct;
   }
  }
?>

By doing this, I do not have to duplicate the work done by my parent's constructor. More importantly, I do not have to worry about the Product class's implementation changing and ours divergingwe have taken code reuse to a whole new level.

Note that PHP will now make sure I call the constructor for DiscountedProduct with six parameters, not just the five that the base class requires. I can similarly create a new version of the destructor:m>

<?php
  public DiscountedClass extends Product
  {
    // etc.

    public function__destruct()
    {
      // it is always a good idea to call my parent's destructor
      parent::__destruct();
    }
  }
?>

To make my Discounted Product class work, I'll want to override one more methodthe get_PricePerUnit method:

<?php

  public DiscountedClass extends Product
  {
    // etc.

    public function get_PricePerUnit()
    {
      return parent::get_PricePerUnit()
             * ((100.0 - $this->discount_percentage) / 100.0);
    }

    // etc.
  }

?>


[Previous] [Contents] [Next]