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
orpublic
- 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();
Top comments (0)