When do we need Interfaces in PHP?


In PHP, interfaces are used to define a set of methods that a class must implement. They provide a way to enforce a contract between objects, ensuring that a class adheres to a specific set of rules.

Here are some scenarios where interfaces are useful in PHP:

  • Implementing Polymorphism: Interfaces allow for polymorphism, which means that different objects can be used interchangeably as long as they implement the same interface. This is useful when you have multiple classes that perform similar tasks but have different implementations.

Example:

interface Shape {
    public function getArea();
}

class Circle implements Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function getArea() {
        return pi() * pow($this->radius, 2);
    }
}

class Square implements Shape {
    private $length;

    public function __construct($length) {
        $this->length = $length;
    }

    public function getArea() {
        return pow($this->length, 2);
    }
}

function printArea(Shape $shape) {
    echo "The area is: " . $shape->getArea();
}

$circle = new Circle(5);
$square = new Square(5);

printArea($circle); // Output: The area is: 78.539816339745
printArea($square); // Output: The area is: 25
  • Enforcing Method Implementation: Interfaces can be used to enforce that a class implements certain methods. This is useful when you have a class that needs to implement a specific set of methods, but you don't want to define the implementation in the interface itself.

Example:

interface Logger {
    public function log($message);
}

class FileLogger implements Logger {
    public function log($message) {
        // Log message to file
    }
}

class DatabaseLogger implements Logger {
    public function log($message) {
        // Log message to database
    }
}

class User {
    private $logger;

    public function __construct(Logger $logger) {
        $this->logger = $logger;
    }

    public function register() {
        // Register user
        $this->logger->log('User registered');
    }
}

$fileLogger = new FileLogger();
$databaseLogger = new DatabaseLogger();

$user1 = new User($fileLogger);
$user1->register(); // Logs message to file

$user2 = new User($databaseLogger);
$user2->register(); // Logs message to database
  • Creating Mock Objects: Interfaces can be used to create mock objects for testing purposes. This is useful when you want to test a class that has dependencies on other objects, but you don't want to use the actual objects in your tests.

Example:

interface Database {
    public function query($sql);
}

class User {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function register() {
        // Register user
        $this->db->query('INSERT INTO users (name, email) VALUES (?, ?)', ['John Doe', '[email protected]']);
    }
}

class MockDatabase implements Database {
    public function query($sql) {
        // Do nothing
    }
}

$mockDb = new MockDatabase();
$user = new User($mockDb);

$user->register(); // Does not actually insert into database


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.