Categories
PHP

Abstract Classes vs. Interfaces

In this tutorial, we explain the difference between abstract classes and interfaces.

An interface specifies methods that classes using the interface must implement. Abstract classes are in many ways similar to interfaces. They can both define methods that the deriving classes must implement, and both can not be instantiated. The following table shows the key differences:

InterfacesAbstract Classes
Define with interface keyword.Define with abstract keyword
Can not be instantiated, a class implements interfaces by using the implements keyword.Can not be instantiated,
required subclass to provide implementation, uses extends keyword to make a subclass.
A (child) class can implement any number of interfaces.In PHP, a (child) class can inherit from one class.
Cannot have properties.May have properties.
All methods must be public.Methods can be public or protected, but not private.
All implemented methods must be public in the child-class.A protected abstract method can turn into public in the child class.
abstract keyword is not required, all methods are abstract.The abstract keyword is required to define an abstract method.
Fully abstract, can not have non-abstract (normal) methods.Partially abstract, can have non-abstract (normal) methods.
An interface can not implement an interface.An abstract class may inherit from a non-abstract class.

Example: Defining an interface

<?php
 interface iABC {
  public function __construct($name);
  public function getName();
 }

Example: Defining an abstract class

<?php
 abstract class DEF {
  public $email;
  public function getEmail() {
   return $this->email;
  }
  //Protected method can be public in child class
  abstract protected function setEmail($email);
 }

Example: Implementing the interface and extending the abstract class:

<?php
 class XYZ extends DEF implements iABC {
  protected $name;
  public function __construct ($name) {
   $this->name = $name;
  }
  // Protected mehtod in abstract class
  // changed to public
  public function setEmail($email) {
   $this->email = $email;
  }
  public function getName() {
   return $this->name;
  }
 }
 
 $c = new XYZ('BrainBell'); 
 $c->setEmail('a@a.com');

 echo $c->getEmail(); # BrainBell
 echo $c->getName();  # a@a.com

PHP OOP Tutorials: