Categories
PHP Programming

PHP interfaces

Interfaces are pure class templates that define functionality. It can contain properties and methods, but no method implementation. See the example below:

interface Chargeable {
    public function getPrice();
}

So any class that implements this interface, will look something like this:

class ShopProduct implements Chargeable {
    // …
    public function getPrice() {
    return ( $this->price – $this->discount );
    }
    // …

When a class implements an interface, it takes on the Type of the interface as well, effectively having more than two types if that same class is also extending other classes, or implementing other interfaces. This way you can join types that are otherwise unrelated when creating a new class.

In PHP you can only inherit from one parent, but you can have multiple interfaces:

class Consultancy extends TimedService implements Bookable, Chargeable {

    // ...
}

Leave a Reply

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