Sobes.tech
Junior

What are interfaces in PHP?

sobes.tech AI

Answer from AI

In PHP, an interface is a contract that describes a set of methods (with their signatures) that a class must implement. It defines "what" a class does, but not "how".

  • Contract: A class implementing an interface is obliged to provide all methods described in this interface, with the same names, parameters, and return types.
  • Type inheritance: Interfaces allow defining types based on behavior, not just class hierarchy. This is useful for polymorphism. You can work with objects of different classes that implement the same interface as if they were of the same type.
  • Multiple inheritance of behavior: PHP does not support multiple class inheritance, but a class can implement multiple interfaces. This allows a class to have behavior from multiple contracts.
  • Separation of concerns: Interfaces help separate the definition of behavior from its implementation.
<?php

// Interface definition
interface Logger
{
    /**
     * Writes a log message.
     * @param string $message Message to write.
     */
    public function log(string $message): void;
}

// Class implementing the interface
class FileLogger implements Logger
{
    private string $filePath;

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

    public function log(string $message): void
    {
        file_put_contents($this->filePath, $message . PHP_EOL, FILE_APPEND);
    }
}

// Another class implementing the same interface
class DatabaseLogger implements Logger
{
    private $dbConnection; // Assumed database connection object

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

    public function log(string $message): void
    {
        // Logic to save to database
        // ...
        echo "Logging to database: " . $message . PHP_EOL;
    }
}

// Using the interface to work with different implementations
function processData(Logger $logger, string $data): void
{
    // Data processing
    // ...
    $logger->log("Processed data: " . $data);
}

$fileLogger = new FileLogger('/var/log/app.log');
$dbLogger = new DatabaseLogger(null); // Stub for database connection example

processData($fileLogger, 'Sample data 1');
processData($dbLogger, 'Sample data 2');

Main differences from abstract classes:

Characteristic Interface Abstract class
Member types Only methods (must be public) Methods (public, protected), properties
Method implementation No implementation (only signatures) Can contain implemented methods
Inheritance A class can implement multiple interfaces A class can inherit only one abstract class
Constructor No Can have a constructor
Members with visibility Only public public, protected
What are interfaces in PHP? — PHP - sobes.tech