×
☰ See All Chapters

PHP Interface

TV remote is an interface between TV and viewer, like this PHP interface is an interface between specification and implementation. PHP interface does not contain any implementation. It is used for setting the standards for the implementation classes to do the implementation. Interface should have only public abstract functions. Using abstract keyword for functions is optional in interfaces.

PHP Interface Syntax

interface Interfacename {

     public  function functionName($pmtr1, $pmtr2, $pmtr3...)  : returnType;

}

To implement an interface, a class must use the implements keyword. A class that implements an interface must implement all of the interface's functions. Single class can implement any number of interfaces. Below is the syntax to implement interface:

class classname implements InterfaceName1 ,InterfaceName2... {

    // class-body

}

PHP Interface Example

<?php

interface Vehicle {

    public function vehicleType();

}

 

interface Car {

    public function name();

}

 

class Ferrari implements Vehicle, Car  {

    public function vehicleType() {

        return "4 wheeler";

    }

   

    public function name() {

        return "Ferrari";

    }

}

 

$ferrari = new Ferrari();

echo "Vehicle Type: " . $ferrari->vehicleType() . "</br>";

echo "Vehicle Name: " . $ferrari->name();

?>

php-interface-0


All Chapters
Author