Skip to content
PHP Logo

How can interfaces in PHP contribute to cleaner and more efficient code, particularly in terms of reusability and scalability?

Using interfaces in PHP can contribute to cleaner and more efficient code by promoting code reusability and scalability. Interfaces allow you to define a set of methods that a class must implement, ensuring consistency across different classes that implement the same interface. This can make your code more modular and easier to maintain, as you can easily swap out implementations without affecting the rest of your codebase.

php
<?php

// Define an interface
interface LoggerInterface {
    public function log($message);
}

// Implement the interface in a class
class FileLogger implements LoggerInterface {
    public function log($message) {
        // Log message to a file
    }
}

// Implement the interface in another class
class DatabaseLogger implements LoggerInterface {
    public function log($message) {
        // Log message to a database
    }
}

// Create an instance of a class that implements the interface
$logger = new FileLogger();
$logger->log('This is a log message');

?>