Abstract Class in PHP

An abstract class provides a partial implementation that other classes can build upon. When a class is declared as abstract, it means that the class can contain incomplete methods that must be implemented in child classes, in addition to normal class members.

images/articles/php/abstract-class-in-php.jpg

In an abstract class, any method can be declared abstract. These methods are then left unimplemented and only their signatures are specified, while their code blocks are replaced by semicolons.

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

For example, the following class has two properties and an abstract method.

abstract class Shape
{
private $x = 100, $y = 100;
abstract public function getArea();
}

If a class inherits from this abstract class, it is then forced to override the abstract method. The method signature must match, except for the access level, which can be made less restricted.

class Rectangle extends Shape
{
public function getArea()
{
return $this->x * $this->y;
}
}

It is not possible to instantiate an abstract class. They serve only as parents for other classes, partly dictating their implementation. However, an abstract class may inherit from a non-abstract (concrete) class.

Abstract Classes and Interfaces

Abstract classes are in many ways similar to interfaces. They can both define member signatures that the deriving classes must implement, and neither one of them can be instantiated. The key difference is that that the abstract class can contain non-abstract members, while the interface cannot.

An abstract class provides a partially implemented base class that dictates how child classes must behave. They are most useful when child classes share some similarities, but differ in other implementations that child classes are required to define. Just like interfaces, abstract classes are useful constructs in object-oriented programming that help developers follow good coding standards.