DEV Community

Cover image for PHP Interfaces
BazengDev
BazengDev

Posted on • Edited on

PHP Interfaces

Interfaces

Interfaces allow you to create code which specifies which methods a class must implement, without any of the methods having their contents defined. Interfaces can be used in different classes this is referred as Polymorphism.

Interfaces are almost like abstract classes , difference being:

  • all methods must be public in an interface unlike in an abstract class where they can be protected or public
  • interfaces are declared with the interface keyword
  • classes can inherit from other classes but still use interfaces unlike abstract classes

Its however important to note all interface methods are abstract without the abstract keyword
To use an interface, a class must use the implements keyword. See example below:

<?php
interface Vehicle{
  public function typeOfFuel();
}
class Lorry implements Vehicle{
  public function typeOfFuel(){
    echo "I use Diesel";
  }
}
class Sedan implements Vehicle{
  public function typeOfFuel(){
    echo "I use Petrol";
  }
}
class Hatchback implements Vehicle{
  public function typeOfFuel(){
    echo "I use electricity";
  }
}

$lorry = new Lorry();
$lorry->typeOfFuel();
echo "\n";
$sedan = new Sedan();
$sedan->typeOfFuel();
echo "\n";
$hatchBack = new Hatchback();
$hatchBack->typeOfFuel();
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)