Inheritance Classes in PHP

php abstract classes
01 December 2024

In PHP, one of the powerful features of object-oriented programming is the use of inheritance classes. Inheritance classes are often misunderstood; this may be due to the fact that a complete understanding of them is not straightforward for everyone. However, these classes are very common for software design and are necessary in some cases.

Inheritance classes act as a template or blueprint for other classes. You cannot directly create an instance of an inheritance class because this class does not have implementation methods but only specifies what methods must be implemented in child classes.

One of the advantages of using inheritance classes is that you can define methods that must exist in all child classes, and through this, you ensure a consistency in the coding style. This topic guarantees that all classes can be designed in a standardized manner.

The use of inheritance classes in real-world applications is very widespread. Especially when you need to have many similar classes with shared functionalities. By doing this, you can define shared sections in the base inheritance class and implement specific sections in child classes.

Don't forget that it is completely permissible to have non-inherited methods alongside inherited methods. These methods can be implemented in the base class and inherited in child classes.

Now, let's look at a simple example of how to define inheritance classes in PHP:


abstract class Vehicle {
abstract public function startEngine();

public function ride() {
echo "Riding the vehicle";
}
}

class Car extends Vehicle {
public function startEngine() {
echo "Car engine started!";
}
}

$car = new Car();
$car->startEngine();
$car->ride();

Line-by-Line Explanation

abstract class Vehicle: Defines an inheritance class named Vehicle.

abstract public function startEngine();: Defines an abstract method that must be implemented in child classes.

public function ride(): Defines a standard method that can be used in child classes.

class Car extends Vehicle: Defines a Car class that inherits from Vehicle.

public function startEngine(): Implements the startEngine method for the Car class.

$car = new Car();: Creates an instance of the Car class.

$car->startEngine();: Calls the startEngine method for the $car instance.

$car->ride();: Calls the ride method inherited from the Vehicle class.

FAQ

?

Why do we use inheritance classes?

?

Can you directly create an instance of an inheritance class?

?

Can non-inherited methods also be defined in these classes?