0
0
PHPprogramming~5 mins

Multiple interface implementation in PHP

Choose your learning style9 modes available
Introduction
Sometimes, a class needs to do many different jobs. Using multiple interfaces lets a class promise to do all those jobs clearly.
When a class must follow rules from more than one source.
When you want to organize different abilities separately and combine them.
When you want to make sure a class has certain methods from different interfaces.
When you want to build flexible and clear code that can grow easily.
Syntax
PHP
class ClassName implements Interface1, Interface2, Interface3 {
    // class methods here
}
Separate interface names with commas.
The class must define all methods from all interfaces it implements.
Examples
This class Athlete promises to run and jump by implementing two interfaces.
PHP
<?php
interface CanRun {
    public function run();
}

interface CanJump {
    public function jump();
}

class Athlete implements CanRun, CanJump {
    public function run() {
        echo "Running fast!\n";
    }
    public function jump() {
        echo "Jumping high!\n";
    }
}

$athlete = new Athlete();
$athlete->run();
$athlete->jump();
Duck can both fly and swim, so it implements both interfaces.
PHP
<?php
interface Flyer {
    public function fly();
}

interface Swimmer {
    public function swim();
}

class Duck implements Flyer, Swimmer {
    public function fly() {
        echo "Flying in the sky!\n";
    }
    public function swim() {
        echo "Swimming in the pond!\n";
    }
}

$duck = new Duck();
$duck->fly();
$duck->swim();
Sample Program
The Book class promises to have both read and write abilities by implementing Reader and Writer interfaces.
PHP
<?php
interface Reader {
    public function read();
}

interface Writer {
    public function write();
}

class Book implements Reader, Writer {
    public function read() {
        echo "Reading the book...\n";
    }
    public function write() {
        echo "Writing notes in the book...\n";
    }
}

$myBook = new Book();
$myBook->read();
$myBook->write();
OutputSuccess
Important Notes
If the class does not implement all methods from all interfaces, PHP will give an error.
Interfaces only declare methods, they do not provide code inside methods.
Multiple interface implementation helps keep code organized and clear.
Summary
A class can implement many interfaces by listing them separated by commas.
This lets the class promise to have all methods from those interfaces.
It helps organize different abilities and keeps code flexible.