How does using interfaces in PHP contribute to modularity and the ability to swap out objects in a system?

Using interfaces in PHP allows for defining a contract that classes must adhere to, promoting modularity by enforcing a consistent API for different objects. This makes it easier to swap out objects with different implementations that still fulfill the interface requirements, without needing to modify the existing code that relies on those objects.

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

class FileLogger implements Logger {
    public function log($message) {
        // Implementation for logging to a file
    }
}

class DatabaseLogger implements Logger {
    public function log($message) {
        // Implementation for logging to a database
    }
}

function logMessage(Logger $logger, $message) {
    $logger->log($message);
}

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

logMessage($fileLogger, "Logging to a file");
logMessage($dbLogger, "Logging to a database");