PHP

Extending Objects

So far, I have seen that object-oriented programming is a powerful way to encapsulate data into new types. I created a Product class, which has a representation of all the "inherent" properties I find in a product being sold in my fictional boating supply web application its name, description, PID, price, and so on.

Extending Existing Classes

However, imagine now that I wanted to have a sale on a few products and offer a certain percentage discount on them. It would be nice if I did not have to add a whole bundle of logic in my web application to manage this, but instead have the Product class be aware of possible discount situations. On the other hand, I do not want to burden the Product class with this extra code, given that most of my products are not on sale.

PHP lets us solve this problem by creating a new class that extends the Product class. This new class, which I might call DiscountedProduct, has all of the data and methods of its parent class but can extend or even change their behavior.

To declare a class that extends another, you use the extends keyword:

<?php
  class DiscountedProduct extends Product
  {
    protected $discount_percentage = 0.0;
  }
?>

In this example, my new DiscountedProduct class extends or inherits from what is typically referred to as the base class, or parent class (Product). So far, it has one new member variable, $discount_percentage, which only it and classes that in turn extend it can see. (Instances of the parent Product class cannot see the member variable.)

Visibility Revisited

Member variables or methods on the base class that are declared public or protected are fully available to any inheriting classes, while properties or methods that are declared as private are not. The one exception to this is if a member function on my base class is protected or publicin that case, I can call it from my inheriting class. The function would then be able to access any private properties or methods:

class ABC
{
  private $abc;
  protected function not_private()
  {
    return $abc;
  }
}
class DEF extends ABC
{
  protected function call_me();
  {
    //
    // when I call this function (which is on my base class)
    // it will have no problems accessing $abc.
    //
    $this->not_private();
  }
}


by BrainBellupdated
Advertisement: