Advertisement
Google Ad Slot: content-top
PHP OOP - Inheritance
PHP - What is Inheritance?
Inheritance in OOP = When a class derives from another class.
Inheritance in Object-Oriented Programming (OOP) allows a child class to acquire the properties and methods of a parent class. In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
Let's look at an example:
Explanation:
- The Car class is inherited from the Vehicle class.
- This means that the Car class can use the public $brand properties as well as the public __construct() methods from the Vehicle class because of inheritance.
- The Car class also has its own method: getBrand().
PHP - Inheritance and the Protected Access Modifier
Explanation:
$brandisprotected, so it cannot be accessed directly outside the class.- But it can be accessed inside a child class (
Car) throughgetBrand().
PHP - Overriding Inherited Methods
nherited methods can be overridden by redefining the methods (use the same name) in the child class.
Let's create a Vehicle class with a describe() method and override it in a Car subclass.
Explanation
1. Base Class (Vehicle)
- Defines
brandandspeedproperties. - Has a
describe()method to display vehicle details.
2. Child Class (Car)
- Inherits
Vehicle. - Adds a new property
$fuelType. - Uses
parent::describe()to call the parent method and then extends it.
3. Overriding
Carredefinesdescribe(), adding fuel type details.
PHP - The final Keyword
The final keyword in PHP is used to prevent method overriding in child classes or stop a class from being inherited.
The following example shows how to prevent class inheritance:
The following example shows how to prevent method overriding: