Introduction
Sometimes, a class needs to do many different jobs. Using multiple interfaces lets a class promise to do all those jobs clearly.
class ClassName implements Interface1, Interface2, Interface3 { // class methods here }
<?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();
<?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();
<?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();
FirstInterface and SecondInterface?implements to indicate a class uses interfaces.implements.interface A { public function foo(); }
interface B { public function bar(); }
class Test implements A, B {
public function foo() { return 'foo'; }
public function bar() { return 'bar'; }
}
$obj = new Test();
echo $obj->foo() . ' ' . $obj->bar();interface X { public function methodX(); }
interface Y { public function methodY(); }
class Demo implements X, Y {
public function methodX() { return 'X'; }
}interface Logger { public function log(string $msg); }
interface Notifier { public function notify(string $msg); }
class System implements Logger, Notifier {
private array $logs = [];
public function log(string $msg) { $this->logs[] = $msg; }
public function notify(string $msg) { echo "Notify: $msg\n"; }
public function getLogs(): array { return $this->logs; }
}
$sys = new System();
$sys->log('Start');
$sys->notify('Alert');
$sys->log('End');
print_r($sys->getLogs());Pass the test and this pattern moves unknown