Interfaces
An interface is a list of method names that a class promises to provide. A class that takes an interface must write every method on the list.
One class takes one interface
The Greeter interface names one method called greet. Host takes the interface with implements and writes the greet method.
<?php
interface Greeter {
public function greet();
}
class Host implements Greeter {
public function greet() {
echo "Hello and welcome\n";
}
}
$host = new Host();
$host->greet();One class takes two interfaces
Host takes Greeter and Farewell in one implements list. The class writes both methods, and both calls print.
<?php
interface Greeter {
public function greet();
}
interface Farewell {
public function bye();
}
class Host implements Greeter, Farewell {
public function greet() {
echo "Hello\n";
}
public function bye() {
echo "Goodbye\n";
}
}
$host = new Host();
$host->greet();
$host->bye();A missing method stops the program
Host takes Greeter but writes no greet method. PHP stops with a fatal error before any object is made.
<?php
interface Greeter {
public function greet();
}
class Host implements Greeter {
}Example
<?php
interface Payment {
public function pay($amount);
}
class CardPayment implements Payment {
public function pay($amount) {
echo "Card paid " . $amount . "\n";
}
}
class CashPayment implements Payment {
public function pay($amount) {
echo "Cash paid " . $amount . "\n";
}
}
function takePayment(Payment $payment, $amount) {
$payment->pay($amount);
}
takePayment(new CardPayment(), 20);
takePayment(new CashPayment(), 15);Key points
- An interface names methods and gives none of them a body.
- The word implements after a class name takes an interface for that class.
- A class that takes an interface must write every method the interface names.
- A class can take more than one interface at once.
- A missing method stops the program with a fatal error at the class line.
- Code can name an interface as a type, and any class that takes it fits that type.
In this example, the Payment interface names one pay method. CardPayment and CashPayment both take the interface and write pay in their own way. The takePayment function names Payment as its parameter type, so both objects fit the same call.
Note
An interface lists what a class does, and the class decides how it does it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A class takes an interface but leaves out one listed method. What happens?