DEV Community


Posted on

When to use PHP abstract classes

OOP and abstract classes are not specific to PHP, but let's see when it makes sense using this programming language.

Abstract classes are meant for inheritance

Abstract classes are generic templates that are extended by other classes to implement their abstract methods.

At this point, you may still struggle to understand why you should use them instead of other known structures, for example:

  • simple classes
  • interfaces

Abstract classes vs. simple classes

Unlike simple classes, abstract classes cannot be instanciated. A child class and the keyword extends are required:

abstract class MyAbstract 
    abstract protected function isValid(): bool;

class MyClass extends MyAbstract 
    protected function isValid(): bool
        return true;// or a more complex condition
Enter fullscreen mode Exit fullscreen mode

isValid() does not mean anything in itself. We just want to force child classes to implement it.

This logic may also explain why you cannot define private abstract methods. It's either public or protected.

Abstract classes vs. interfaces

Abstract classes can contain non-abstract methods and properties child classes do not have to [re-]implement (e.g., common implementations and properties available for all child classes).

Both abstract classes and interfaces will force other classes to implement specific methods, but abstract classes are meant for inheritance, whereas interfaces are used to achieve polymorphism.

In short:

  • if you need to share common features and properties across the entire hierarchy (all child classes), use an abstract
  • if you need to force an implementation but with additional parameters (only if you define default values), use an abstract
  • if you start adding lots of abstract methods in your abstract class, it might be better to use an interface

Top comments (0)