OOP Interface PHP: How to Set Rules for Classes

oop interface php

PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves problems with code organization and flexibility.

In this article, we will cover the following topics:

  • Understanding the OOP interface in PHP and how it works.
  • How to use multiple interfaces in PHP.
  • The difference between interfaces and abstract classes.
  • PHP built-in interfaces.
  • Examples.

Let’s start with the definition and how it works.

Understand What an Interface Is in PHP

An interface in PHP specifies a collection of methods that a class must implement. It does not contain method bodies, only their names and parameters.

Here are the key points:

  • Interfaces define method names but not their code.
  • Classes that implement an interface must define all its methods.
  • A class can implement multiple interfaces.
  • Interfaces help keep code structured and reusable.

Here is a quick example:

interface Vehicle {
    public function move();
}

class Car implements Vehicle {
    public function move() {
        echo "Car moves to my country";
    }
}

class Bike implements Vehicle {
    public function move() {
        echo "Bike moves to my club";
    }
}

$car = new Car();
$car->move();  

$bike = new Bike();
$bike->move();  

This example shows that Car and Bike follow the Vehicle interface. Both classes must define the move() method.

If a class does not define all methods declared in the interface with the same name and parameters. PHP will throw a fatal error:

PHP Fatal error:  Class Bike contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Vehicle::move) in /interface.php on line 13

So, you need to implement all methods from the interface in PHP to avoid that error.

Let’s move on to understanding inheritance between an interface and a class.

Understand the implements Keyword in PHP

The implements keyword in PHP tells a class to follow an interface. It must define all the methods declared in the interface when a class uses implements.

Here is how implements works with the class:

  • A class can implement one or more interfaces.
  • The interface only defines method names, and the class provides their code.
  • PHP throws an error if a class does not define all interface methods.

Here is an example:

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

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

$logger = new FileLogger();
$logger->log("System error"); 

Here is the output:

Logging to a file: System error

Here, FileLogger implements the Logger interface. It must define the log() method.

In the section below you will learn how to implement multiple interfaces in PHP.

Multiple Interfaces in PHP

A class in PHP can implement multiple interfaces with separate them with commas. This allows a class to follow multiple sets of rules and makes code more flexible.

  • A class can implement multiple interfaces.
  • It must define all methods from each interface.
  • Interfaces help organize code without using inheritance.

Here is an example:

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

interface Printer {
    public function print();
}

class MultiFunctionDevice implements Logger, Printer {
    public function log($message) {
        echo "Logging: " . $message;
    }

    public function print() {
        echo "Printing document";
    }
}

$device = new MultiFunctionDevice();
$device->log("Data saved"); // Output: Logging: Data saved
$device->print(); // Output: Printing document

Here, MultiFunctionDevice follows both Logger and Printer, so it must define log() and print().

In the following section, you will learn the difference between interfaces and abstract classes.

The Difference Between Interfaces and Abstract Classes

FeatureInterfaceAbstract Class
MethodsOnly method signatures (no code)Can have method signatures and method bodies
PropertiesNo propertiesCan have properties
Multiple ImplementationsA class can implement multiple interfacesA class can extend only one abstract class
Access ModifiersAll methods must be publicMethods can be public, protected, or private
UsageDefines a contract for multiple classesUsed when classes share some behavior but need different implementations

In the following section, we will take a look at the built-in interfaces in PHP.

PHP Built-in Interfaces

PHP has several built-in interfaces that help developers work with common programming patterns. These interfaces are part of PHP’s Standard PHP Library (SPL) and other core features.

Here are the common built-in interfaces:

  • Countable
  • ArrayAccess
  • Iterator
  • IteratorAggregate
  • Serializable
  • Throwable

Let’s take each one in-depth:

Countable

Allows objects to be used with count().

Here is an example:

class FruitBasket implements Countable {
    private $fruits = ["Apple", "Banana", "Orange"];

    public function count() {
        return count($this->fruits);
    }
}

$basket = new FruitBasket();
echo count($basket); // Output: 3

ArrayAccess

Allows an object to be accessed like an array.

For example:

class CustomArray implements ArrayAccess {
    private $data = [];

    public function offsetSet($key, $value) {
        $this->data[$key] = $value;
    }

    public function offsetExists($key) {
        return isset($this->data[$key]);
    }

    public function offsetUnset($key) {
        unset($this->data[$key]);
    }

    public function offsetGet($key) {
        return $this->data[$key] ?? null;
    }
}

$array = new CustomArray();
$array["name"] = "FlatCoding";
echo $array["name"]; // Output: FlatCoding

Iterator

Defines methods to make an object iterable with foreach.

class SimpleIterator implements Iterator {
    private $values = [1, 2, 3];
    private $index = 0;

    public function rewind() {
        $this->index = 0;
    }

    public function current() {
        return $this->values[$this->index];
    }

    public function key() {
        return $this->index;
    }

    public function next() {
        $this->index++;
    }

    public function valid() {
        return isset($this->values[$this->index]);
    }
}

$iterator = new SimpleIterator();
foreach ($iterator as $key => $value) {
    echo "$key => $value\n";
}

Output:

0 => 1
1 => 2
2 => 3

IteratorAggregate

Allows an object to return an iterator instead of implementing all Iterator methods.

For example:

class Collection implements IteratorAggregate {
    private $items = ["A", "B", "C"];

    public function getIterator() {
        return new ArrayIterator($this->items);
    }
}

$collection = new Collection();
foreach ($collection as $item) {
    echo $item . "\n";
}

Here is the output:

A
B
C

Serializable

Defines how an object is converted into a storable format and restored.

class Person implements Serializable {
    private $name;

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

    public function serialize() {
        return serialize($this->name);
    }

    public function unserialize($data) {
        $this->name = unserialize($data);
    }

    public function getName() {
        return $this->name;
    }
}

$person = new Person("Alice");
$serializedData = serialize($person);
echo $serializedData . "\n"; // Output: Serialized string

$unserializedPerson = unserialize($serializedData);
echo $unserializedPerson->getName(); // Output: Alice

Output:

C:6:"Person":12:{s:5:"Alice";}
Alice

Throwable

Used for error handling. Both Exception and Error classes implement it.

Here is an example:

try {
    throw new Exception("Something went wrong");
} catch (Throwable $e) {
    echo $e->getMessage(); // Output: Something went wrong
}

Wrapping Up

You learned in this article how the interface in OOP PHP helps improve code structure. Here is a quick recap of the key points:

  • Interfaces define methods that a class must implement, but do not include their code.
  • The implements keyword forces a class to follow an interface. It makes sure that it defines all methods.
  • A class can implement multiple interfaces, which allows it to follow multiple sets of rules.
  • Abstract classes differ from interfaces. That allows method bodies and properties.
  • PHP provides built-in interfaces, such as Countable, ArrayAccess, and Iterator to help manage common patterns in code.

FAQ’s

What is an interface in PHP?

An interface in PHP defines a set of methods that a class must implement. It does not include method bodies, only method names and parameters.

Can a class implement multiple interfaces in PHP?

Yes, a class can implement multiple interfaces by separating them with commas. The class must define all methods from each interface.

How is an interface different from an abstract class?

  • An interface only defines method signatures and cannot have properties.
  • An abstract class can have both method implementations and properties.
  • A class can implement multiple interfaces but can only extend one abstract class.

What happens if a class does not implement all methods from an interface?

PHP throws a fatal error because the class does not meet the interface’s contract.

Why use interfaces in PHP?

Interfaces make code more organized, reusable, and flexible by enforcing a structure that multiple classes can follow.

What are some built-in PHP interfaces?

PHP includes built-in interfaces such as Countable, ArrayAccess, Iterator, IteratorAggregate, Serializable, and Throwable. These help with tasks like iteration, serialization, and error handling.

When should I use an interface instead of an abstract class?

Use an interface when different classes need to follow the same structure but do not share common behavior. Use an abstract class when multiple classes need some shared functionality.
Previous Article

Inheritance in PHP: Share Code from Class to Class & Examples

Next Article

PHP Null: How to Assign and Check for Null Values

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.