PHP Interfaces
An interface is a list of public methods that a class MUST provide. It says what has to exist but leaves out how each method works.
You declare one with the interface keyword, and every method in it has to be public.
A class signs up for an interface with the implements keyword, and from then on it has to implement all of the interface's methods.
In the next example, the Animal interface declares a single public method, makeSound(). Because Cat and Dog both implement Animal, each of them has to include makeSound():
Example
Cat and Dog each give makeSound() their own body to satisfy the Animal interface:
Output: PHP script
<?php
// Define the interface
interface Animal {
public function makeSound();
}
// Implement the interface in a class
class Cat implements Animal {
public function makeSound() {
echo "Meow";
}
}
// Implement the interface in another class
class Dog implements Animal {
public function makeSound() {
echo "Woff";
}
}
$cat = new Cat();
$cat->makeSound();
$dog = new Dog();
$dog->makeSound();
?>
Interface syntax
How an interface declaration is written:
<?php
interface InterfaceName {
public function method1();
public function method2();
}
?>
Implementing an interface
How a class implements an interface:
<?php
class ClassName implements InterfaceName{
public function method1() {
// some code
}
public function method2(){
// some code
}
}
?>
PHP - Interfaces vs. Abstract Classes
Interfaces have a lot in common with abstract classes, but they differ in several ways:
- An abstract class can have properties; an interface cannot
- Interface methods are always public, whereas abstract methods may be public or protected
- Every interface method is abstract, so it has no implementation in code, and you don't need to write the
abstractkeyword - A class can extend another class and implement an interface at the same time
The big benefit of interfaces is that different classes can be used in the same way. When one or more classes share an interface, we call this "polymorphism".
PHP - Using Interfaces
This time the Animal interface declares two public methods, fromFamily() and makeSound(). Cat and Dog implement the interface, so each class has to include both methods:
Example
Cat and Dog both implement the two methods of the interface:
Output: PHP script
<?php
interface Animal {
public function fromFamily();
public function makeSound();
}
class Cat implements Animal {
public function fromFamily() {
echo "From family: Felidae (Relatives: lions, tigers, jaguars, lynx, cougars, and cheetahs).<br>";
}
public function makeSound() {
echo "Sound: Meow.";
}
}
class Dog implements Animal {
public function fromFamily() {
echo "From family: Canidae (Relatives: wolves, foxes, coyotes, jackals, and domestic dogs).<br>";
}
public function makeSound() {
echo "Sound: Woff.";
}
}
echo "<h3>Cats</h3>";
$cat = new Cat();
$cat->fromFamily();
$cat->makeSound();
echo "<h3>Dogs</h3>";
$dog = new Dog();
$dog->fromFamily();
$dog->makeSound();
?>