PHP Basic Tutorial
MySQL Connection
PHP Advanced
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:
Try it yourself
Try it yourself
$brand
is protected
, so it cannot be accessed directly outside the class.Car
) through getBrand()
.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.
Try it yourself
1. Base Class (Vehicle
)
brand
and speed
properties.describe()
method to display vehicle details. 2. Child Class (Car
)
Vehicle
.$fuelType
.parent::describe()
to call the parent method and then extends it.3. Overriding
Car
redefines describe()
, adding fuel type details.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:
Try it yourself
The following example shows how to prevent method overriding:
Try it yourself