An interface in PHP is a way to specify what methods a class must implement. It provides a contract for classes that implement the interface to ensure they adhere to a specific structure. Interfaces are useful when you want to define a set of methods that multiple classes should implement, without defining how those methods should work.
interface Animal {
public function makeSound();
public function eat($food);
}
class Dog implements Animal {
public function makeSound() {
echo "Woof! Woof!";
}
public function eat($food) {
echo "The dog eats " . $food;
}
}
class Cat implements Animal {
public function makeSound() {
echo "Meow! Meow!";
}
public function eat($food) {
echo "The cat eats " . $food;
}
}
In this example, the `Animal` interface declares two methods: `makeSound` and `eat`. Any class that implements this interface is required to define these methods.
Interfaces can extend other interfaces, using the `extends` keyword. This allows one interface to inherit the method signatures from another.
interface Mammal {
public function breathe();
}
interface Animal extends Mammal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
echo "Woof! Woof!";
}
public function breathe() {
echo "The dog breathes in and out.";
}
}
A single class can implement multiple interfaces. This is how PHP achieves multiple inheritances.
interface A {
public function doSomethingA();
}
interface B {
public function doSomethingB();
}
class Example implements A, B {
public function doSomethingA() {
echo "Doing something A!";
}
public function doSomethingB() {
echo "Doing something B!";
}
}
You can use interfaces for type hinting in function or method arguments. This ensures that the provided object adheres to the interface.
function letAnimalEat(Animal $animal, $food) {
$animal->eat($food);
}
$dog = new Dog();
$cat = new Cat();
letAnimalEat($dog, 'bone'); // The dog eats bone
letAnimalEat($cat, 'fish'); // The cat eats fish
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here