Sobes.tech
Junior

What are interfaces in PHP and what is their role in development?

sobes.tech AI

Answer from AI

An interface in PHP is a contract that defines a set of methods that a class implementing it must realize. The interface contains only method signatures (name, parameters, and return type if specified), without implementation.

Roles of interfaces:

  • Abstraction: They allow defining abstract behavior without concerning about specific implementation.
  • Contract: They guarantee that all classes implementing the interface will have a certain set of methods.
  • Polymorphism: They enable working with objects of different classes that implement the same interface in a uniform way.
  • Loose coupling: They reduce dependencies between classes as they interact through the interface rather than directly.
  • Testing: They simplify unit testing by allowing the use of stubs or mocks that implement the interface.

Example of defining an interface:

<?php
// Interface for objects that can be saved
interface Savable
{
    public function save(): bool;
    public function load(int $id): ?array;
}

Example of implementing the interface with a class:

<?php
// User class implements Savable interface
class User implements Savable
{
    private int $id;
    private string $name;

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

    public function save(): bool
    {
        // Logic to save user to database
        echo "Saving user " . $this->name . PHP_EOL;
        $this->id = rand(1, 1000); // Simulate ID assignment
        return true;
    }

    public function load(int $id): ?array
    {
        // Logic to load user from database
        echo "Loading user with ID " . $id . PHP_EOL;
        if ($id > 0) {
            $this->id = $id;
            $this->name = "Loaded User " . $id;
            return ['id' => $this->id, 'name' => $this->name];
        }
        return null;
    }
}

Example of using polymorphism with the interface:

<?php
// Function accepts any object implementing Savable
function processSavable(Savable $item): void
{
    if ($item->save()) {
        echo "Object saved successfully." . PHP_EOL;
    }
}

$user = new User("Alice");
processSavable($user); // Passing a User object that implements Savable