DEV Community 👩‍💻👨‍💻

Cover image for PHP Interfaces
Samuel K.M
Samuel K.M

Posted on • Updated 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

Top comments (0)

🌚 Life is too short to browse without dark mode