Although abstract classes let you provide some measure of implementation, interfaces are pure templates. An interface can only define functionality; it can never implement it. An interface is declared with the interface keyword. It can contain properties and method declarations but not method bodies.

<?php
interface Chargeable
{    
    public function getPrice(): float;
}

As you can see, an interface looks very much like a class. Any class that incorporates this interface commits to implementing all the methods it defines, or it must be declared abstract.A class can implement an interface using the implements keyword in its declaration. Once you have done this, the process of implementing an interface is the same as extending an abstract class that contains only abstract methods. Now I will make the ShopProduct class implement Chargeable

<?php
class ShopProduct implements Chargeable
{    
    protected $price;
    public function getPrice(): float    
    {        
        return $this->price;    
    } 
}
<?php
class Consultancy extends TimedService implements Bookable, Chargeable
{    
    // ...
}

Notice that the Consultancy class implements more than one interface. Multiple interfaces follow the implements keyword in a comma-separated list.PHP only supports inheritance from a single parent, so the extends keyword can precede a single class name only.


This post is part of series:

1 - Object Oriented Programming Concept2 - Classes3 - Objects4 - Methods5 - Constructors6 - Arguments and Types7 - Static Methods and Properties8 - Constant Properties9 - Abstract Classes10 - Interfaces11 - Traits
OOP#OOPPHP#PHP

Comments (0)