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.)