PHP Interfaces

Creating contracts for your classes

🔌 What are PHP Interfaces?

Interfaces define a contract that classes must follow. They specify which methods a class must implement without defining how those methods work, ensuring consistent behavior across different classes.


<?php
// Simple interface example
interface Animal {
    public function makeSound();
}

class Dog implements Animal {
    public function makeSound() {
        return "Woof!";
    }
}
?>
                                    

Why Use Interfaces?

📋

Contracts

Define what methods classes must have

Consistency Standards
🔄

Flexibility

Multiple classes can implement same interface

Polymorphism Interchangeable
🧩

Multiple Interfaces

Classes can implement many interfaces

Versatile Modular
✅

Type Safety

Ensure objects have required methods

Reliable Predictable

🔹 Basic Interface Example

Interfaces define method signatures that implementing classes must provide. All methods in an interface are automatically public and cannot contain implementation code.

<?php
// Define an interface
interface PaymentMethod {
    public function processPayment($amount);
    public function refund($transactionId);
}

// Implement the interface
class CreditCard implements PaymentMethod {
    public function processPayment($amount) {
        return "Processing $$amount via Credit Card";
    }
    
    public function refund($transactionId) {
        return "Refunding transaction: $transactionId";
    }
}

// Use the class
$payment = new CreditCard();
echo $payment->processPayment(100);
// Output: Processing $100 via Credit Card
?>

Output:

Processing $100 via Credit Card

🔹 Multiple Implementations

Different classes can implement the same interface in their own way, providing flexibility while maintaining a consistent structure for your code.

<?php
interface Vehicle {
    public function start();
    public function stop();
}

class Car implements Vehicle {
    public function start() {
        return "Car engine started";
    }
    
    public function stop() {
        return "Car engine stopped";
    }
}

class Motorcycle implements Vehicle {
    public function start() {
        return "Motorcycle engine started";
    }
    
    public function stop() {
        return "Motorcycle engine stopped";
    }
}

// Both work the same way
$car = new Car();
$bike = new Motorcycle();

echo $car->start() . "<br>";
echo $bike->start();
?>

Output:

Car engine started

Motorcycle engine started

🔹 Implementing Multiple Interfaces

A class can implement multiple interfaces by separating them with commas, allowing you to combine different contracts into a single class.

<?php
interface Flyable {
    public function fly();
}

interface Swimmable {
    public function swim();
}

// Implement multiple interfaces
class Duck implements Flyable, Swimmable {
    public function fly() {
        return "Duck is flying";
    }
    
    public function swim() {
        return "Duck is swimming";
    }
}

$duck = new Duck();
echo $duck->fly() . "<br>";
echo $duck->swim();
?>

Output:

Duck is flying

Duck is swimming

🔹 Interface Inheritance

Interfaces can extend other interfaces, creating a hierarchy of contracts that build upon each other for more complex requirements.

<?php
interface Shape {
    public function getArea();
}

interface ColoredShape extends Shape {
    public function getColor();
}

class Circle implements ColoredShape {
    private $radius = 5;
    private $color = "red";
    
    public function getArea() {
        return 3.14 * $this->radius * $this->radius;
    }
    
    public function getColor() {
        return $this->color;
    }
}

$circle = new Circle();
echo "Area: " . $circle->getArea() . "<br>";
echo "Color: " . $circle->getColor();
?>

Output:

Area: 78.5

Color: red

🔹 Interface Constants

Interfaces can contain constants that are accessible to all implementing classes, providing shared values across your application.

<?php
interface Database {
    const HOST = "localhost";
    const PORT = 3306;
    
    public function connect();
}

class MySQL implements Database {
    public function connect() {
        return "Connecting to " . self::HOST . ":" . self::PORT;
    }
}

$db = new MySQL();
echo $db->connect() . "<br>";
echo "Default port: " . Database::PORT;
?>

Output:

Connecting to localhost:3306

Default port: 3306

🔹 Type Hinting with Interfaces

Use interfaces as type hints to ensure functions receive objects that implement specific methods, making your code more reliable and maintainable.

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

class FileLogger implements Logger {
    public function log($message) {
        return "Logging to file: $message";
    }
}

class DatabaseLogger implements Logger {
    public function log($message) {
        return "Logging to database: $message";
    }
}

// Function accepts any Logger
function saveLog(Logger $logger, $message) {
    return $logger->log($message);
}

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

echo saveLog($fileLogger, "Error occurred") . "<br>";
echo saveLog($dbLogger, "User logged in");
?>

Output:

Logging to file: Error occurred

Logging to database: User logged in

💡 Key Points to Remember:

  • Interfaces define method signatures without implementation
  • All interface methods are automatically public
  • Classes use implements keyword to use interfaces
  • A class can implement multiple interfaces
  • Interfaces can extend other interfaces
  • Interfaces can contain constants but not properties
  • All methods declared in an interface must be implemented

🧠 Test Your Knowledge

Can a class implement multiple interfaces?