xxxxxxxxxx
//PHP - What are Interfaces?
//Interfaces allow you to specify what methods a class should implement.
//Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism".
//Interfaces are declared with the interface keyword
<?php
interface Animal {
public function makeSound();
}
class Cat implements Animal {
public function makeSound() {
echo "Meow";
}
}
$animal = new Cat();
$animal->makeSound();
?>
//output: Meow
xxxxxxxxxx
<?php
// Interface definition
interface Cars {
public function carDetails();
}
// Class definitions
class Tata implements Cars {
public function carDetails() {
echo " Tata Car Details \n";
}
}
class Audi implements Cars {
public function carDetails() {
echo " Audi Car Details \n";
}
}
class Honda implements Cars {
public function carDetails() {
echo " Honda Car Details \n";
}
}
class Maruti implements Cars {
public function carDetails() {
echo " Maruti Car Details \n";
}
}
// Create a list of Cars object
$objTata = new Tata();
print $objTata->carDetails();
$objAudi = new Audi();
print $objAudi->carDetails();
$objHonda = new Honda();
print $objHonda->carDetails();
$objMaruti = new Maruti();
print $objMaruti->carDetails();
?>
A PHP interface defines a contract which a class must fulfill. If a PHP class is a blueprint for objects, an interface is a blueprint for classes.
Interfaces allow you to specify what methods a class should implement.
Any class implementing a given interface can be expected to have the same behavior in terms of what can be called, how it can be called, and what will be returned.
xxxxxxxxxx
<?php
// Interface definition
interface Cars {
public function carDetails();
}
// Class definitions
class Tata implements Cars {
public function carDetails() {
echo " Tata Car Details \n";
}
}
$objTata = new Tata();
print $objTata->carDetails();
?>
xxxxxxxxxx
interface MyInterface {
public function myMethod();
public function anotherMethod($param);
}