What is Interface in PHP 7

What is Interface in PHP 7



What is Interface

An Interface allow user to define public methods that a class must implement. Or in other words if a class “implements” a interface that class must use functions defined in “Interface”. We can have functions in interface without body similar to abstract functions.





Here is the code example for Interface in PHP



<?php

// A simple Parent Class
class Vehicles
{
    public $carEngine = '300MG';
    public function raceAdjustment()
    {
        return $this->carEngine;
    }
}


// An Interface with function
interface Color
{
    public function applyColor();
}



// Child class extending parent class and implementing Interface
class Bmw extends Vehicles implements Color
{
    // function from interface in class (must class if implement 
    // interface)
    public function applyColor()
    {
        return 'red';
    }


    public function getStats()
    {
        return $this->carEngine . ' Has Body Color -' . $this->applyColor(  );
    }
}



$bmw = new Bmw();


echo $bmw->getStats();