Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What are interfaces in PHP?

Saad Akbar

Overview

An interface is generally regarded as a higher level of abstraction. It allows the user to specify the public methods that a class must implement. This reduces the complexity associated with these methods.

The structure of an interface is similar to a class, but there are significant differences that cannot be overlooked. For instance, the class keyword here is replaced with the interface keyword. Moreover, only function prototypes are available in the interface.

Note: Interface declaration requires the use of the keyword interface.

Syntax

<?php
interface Interface_Name 
{
  public function FunctionName();  
}
?>
The syntax to write an interface in PHP

The keyword implement allows linking the interface with its class.

Code example

<?php

interface Animal {
  public function move();
}

class Lion implements Animal {
  public function move() {
    echo "Lion moves.";
  }
}

class Dog implements Animal {
  public function move() {
    echo "Dog moves.";
  }
}

class Cow implements Animal {
  public function move() {
    echo "Cow moves.";
  }
}
class Horse implements Animal {
  public function move() {
    echo "Horse moves.";
  }
}

//  animals
$lion = new Lion();
$dog = new Dog();
$cow = new Cow();
$horse = new Horse();
$animals = array($lion, $dog, $cow, $horse);

// each animal's movement 
foreach($animals as $animal) {
  $animal->move();
  echo "\n";
}
?>
Code example to implement an interface in PHP

Explanation

In the code above, the Lion, Dog , Cow and Horse classes implement the Animal interface. They all must implement the move() function because it is provided in the Animal interface.

RELATED TAGS

php
RELATED COURSES

View all Courses

Keep Exploring