Expanding Your Fleet with Inheritance
Expanding Your Fleet with Inheritance
It's great to see you again! In our previous lessons, you've built a strong foundation with PHP classes. You've learned how to handle properties, methods, and visibility, taking control of your data using getters and setters. Now, we're moving forward to an important and exciting concept: inheritance.
What is Inheritance?
Inheritance is a fundamental concept in Object-Oriented Programming (OOP). It allows one class, known as the child class, to inherit properties and methods from another class, called the parent class.
Imagine you have a basic spacecraft design (the parent class) that includes general features like a hull, engine, and control system. You can then create more specific types of spacecraft (the child classes) such as shuttles or cargo ships. These child classes inherit all the general features of the basic spacecraft but can also have their own unique characteristics.
For example, while the basic Spacecraft has essential elements needed for space travel, a Shuttle might have additional features like passenger seating. This means you can use the shared features from the parent Spacecraft class in your Shuttle class, saving time and keeping your code organized and efficient.
What You'll Learn
In this lesson, you will master inheritance, a key concept in Object-Oriented Programming (OOP). Inheritance allows one class to inherit properties and methods from another class, promoting code reuse and logical organization of your code.
Here's a quick overview:
- Understanding the Basics of Inheritance: You'll learn how one class can inherit features from another class.
- Creating Subclasses: You'll see how to create subclasses that extend the functionality of existing classes.
- Using the
parentKeyword: You'll understand how to call parent class methods and properties in the subclass.
Let's look at a practical example. Imagine you have a Spacecraft class and you want to create a more specific type of spacecraft, a Shuttle.
Now, let's create a Shuttle class that inherits from Spacecraft:
In this example, the Shuttle class inherits the name property and constructor from the Spacecraft class. We also added a new property, passengerCapacity, specific to the Shuttle class.
