What is Interface in PHP?

An interface is a blueprint that defines required methods without implementing them. A class that implements an interface must define all its methods. Interfaces allow multiple inheritance and help build loosely coupled, scalable systems. All interface methods must be public and cannot have bodies. Interfaces ensure consistency across different classes.

1. Basic Interface Example


interface Animal {
    public function makeSound();
}

class Dog implements Animal {
    public function makeSound() {
        return "Woof!";
    }
}

$dog = new Dog();
echo $dog->makeSound(); // Output: Woof!

File: interface_basic.php

2. Multiple Interfaces


interface A {
    public function methodA();
}

interface B {
    public function methodB();
}

class MyClass implements A, B {
    public function methodA() {
        return "A";
    }

    public function methodB() {
        return "B";
    }
}

$obj = new MyClass();
echo $obj->methodA(); // Output: A
echo $obj->methodB(); // Output: B

File: multiple_interfaces.php

3. Key Rules of Interfaces

Rule Description
Cannot have property declarations Only method declarations are allowed
All methods are public Must be public (implicitly or explicitly)
No method body Only method signatures (no implementation)
Class must use implements Not extends (like abstract)
Supports multiple interfaces Yes, comma-separated