Let’s talk about inheritance. We’ve talked about how to extend a class and covered encapsulation. Inheritance is when a class extends another class and inherits the properties and methods of that class. The main advantage to this is the ability to use a parent class and modify it for a special use without actually modifying the actual class itself. You can create new methods and properties that can be used alongside the parent’s methods and properties.
Inheritance goes 1 way. Meaning, any methods or properties created in the child class, can not be used in the parent class. If we had Class B extend Class A, then Class B has access to all methods and properties of Class A, but not vice versa. If we had an extra class called Class C that extends Class B, then Class C has access to all methods and properties to both Class A and Class B.
Difference between Inheritance and Encapsulation
Remember that these are 2 concepts to object oriented programming. Encapsulation is the concept of how properties and methods are accessed. Inheritance is the concept of a subclass containing all the properties and methods of the parent class it extends.
It’s important to understand these 2 concepts as they are used regularly in PHP OOP. Actually, these 2 concepts apply to all programming languages that use object oriented programming. Such as Java, C#, or C++.
We’ve already seen an example of this in our CanadianPet class. Our CanadianPet class inherits all the properties and methods of the Pet class. By doing this, we don’t have to copy and paste code. Instead, we can override certain properties or methods in our subclass. You can also reuse code by doing so.
Now we’re learning the true power of object oriented programming. Inheritance is an important concept to understand. If you don’t fully understand, then go here for a more thorough explanation.