Implementing Multiple Interface
In PHP, a class can implement multiple interfaces by separating them with commas in the implements
clause. Here's the syntax for implementing multiple interfaces:
interface Interface1 {
public function method1();
}
interface Interface2 {
public function method2();
}
class MyClass implements Interface1, Interface2 {
public function method1() {
// Implementation for method1
}
public function method2() {
// Implementation for method2
}
// ... add more methods as needed
}
In this example, MyClass
implements both Interface1
and Interface2
. The class must provide implementations for all the methods declared in both interfaces.
If a class implements multiple interfaces that have methods with the same name, it must provide a single implementation for that method. PHP does not support method overloading, so the method signature (including the parameters) must be the same in all interfaces.
Here's another example demonstrating a case where two interfaces have a method with the same name:
interface Logger {
public function log($message);
}
interface Messenger {
public function log($message);
}
class MyService implements Logger, Messenger {
public function log($message) {
// Implementation for log method
}
// ... add more methods as needed
}
In this case, MyService
implements both Logger
and Messenger
, and it provides a single implementation for the log
method that satisfies the requirements of both interfaces.
Thank you.