Understanding and Utilizing Abstract Classes in PHP

Andrei Birta
2 min readJan 27, 2023

--

In PHP, an abstract class is a class that cannot be instantiated on its own, but can be extended by other classes. An abstract class is used as a blueprint or template for other classes and it contains methods that must be implemented by its subclasses. These methods are known as abstract methods. Abstract classes are used to define a common set of methods and properties that must be implemented by all classes that inherit from it.

An abstract class is defined using the “abstract” keyword, and an abstract method is defined using the “abstract” keyword as well, followed by the method signature. For example:

abstract class Shape {
abstract public function area();
}

This is an example of an abstract class called “Shape”, which contains an abstract method called “area()”. This method must be implemented by any class that inherits from Shape.

A class that inherits from an abstract class is called a concrete class. In order to inherit from an abstract class, a class must use the “extends” keyword. For example:

class Square extends Shape {
private $side;

public function __construct($side) {
$this->side = $side;
}

public function area() {
return $this->side * $this->side;
}
}

An abstract class can also have non-abstract methods, which can have an implementation. These methods can be overridden by the subclasses, but they don’t have to, they can use the implementation given by the abstract class.

You can use abstract class to define a contract, it ensures that all the classes that implements this contract will have certain methods and properties. For example, you can have a Animal abstract class with a speak() method, this way you can ensure that all the classes that extends this Animals class will have a speak() method.

One of the main advantages of using abstract class is that it allows you to define a common interface for a group of related classes, making the code more organized and easier to maintain. It also makes it easier to update the code, changes only need to be made in the abstract class and not in every single class that inherits from it.

In conclusion, an abstract class in PHP is a class that cannot be instantiated on its own, but can be extended by other classes. It serves as a blueprint or template for other classes and contains methods that must be implemented by its subclasses. It allows you to define a common interface for a group of related classes and makes the code more organized and easier to maintain.

Get more valuable insights and tips by following me!
Also check my list of articles about the PHP or different type of architecture.

--

--