PHP OOPs - Interfaces

What is an interface in php?

An interface contains All abstract methods by default. An interface doesn't have any common methods. Methods of interface do not have any implementation part. Methods of interface are only declared.

When one or more classes use the same interface, it is referred to as "polymorphism

All methods of interface must be implemeted in its child class.

Interfaces are declared using the interface keyword.

Interfaces must be implemented by using implements keyword.

Interfaces can be extended like classes using the extends operator.

Interfaces can define method names and arguments but not the implementation of the methods.

Characteristic of the interface.

All methods inside interface are abstract method.

All the methods inside interfaces must be public.

Interfaces are different from classes as the class can inherit from one class only whereas the class can implement one or more interfaces.

Variables can not be declared inside interface.

 

PHP Syntax:

<?php
interface InterfaceName {
  public function abstractMethod1();
  public function abstractMethod2($param1, $param2);
 
}

class ChildClass implements InterfaceName
{  
    //All methods of interface must be implemeted
}
?>

PHP Example :

<?php
// Code by aryatechno!
interface Car {
  public function color();
}

class Model implements Car {
  public function color() {
    echo "My xuv car is Red.";
  }
}

$car = new Model();
$car->color();
?>

Output:

My xuv car is Red.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

55463