Interface in PHP

In this article I am going to explain how to use interface in PHP.
  • 1409

Introduction

Most developers know that they cannot use multiple inheritance in PHP. To allow this feature, they use an interface. An interface allows you to define a standard structure for your classes. To define an interface you must use the interface keyword and all methods that are declared in an interface must be public. To implement an interface, the "implements" operator is used. You can implement interfaces that share a function name. You can extend an interface by the use of the "extend" keyword. If we talk about it in simple terms, an interface is like a class using the interface keyword and only contains function declarations (in other words a function without a body).

Syntax

access_specifier Interfacee interface_name //access_specifier is public or no_modifier
{
return_type methodname1(arg list); // Method declaration
return_type methodname2(arg list);
type variable_name1 = value1; // Variable declaration Note: variables should be constant.
type variable_name2 = value2
-----------
-----------
}

Example of interface in PHP

<?php

interface MyInterface

{

public function add($val1,$val2);

public function sub($val1,$val2);

}

interface MyInterface1 extends Myinterface

{

public function mul($val1,$val2);

public function div($val1,$val2);

}

class Myclass implements MyInterface1

{

public function add($val1,$val2)

{

$sum=$val1+$val2;

echo "Result of Addition is : ". $sum. "</br>";

}

public function sub($val1,$val2)

{

$sub=$val1-$val2;

echo "Result of Substraction is : ". $sub. "</br>";

}

public function mul($val1,$val2)

{

$mul=$val1*$val2;

echo "Result of Multiplication is : ". $mul. "</br>";

}

public function div($val1,$val2)

{

$div=$val1/$val2;

echo "Result of Division is : ". $div. "</br>";

}

}

$obj= new Myclass();

$obj->sub(2,1);

$obj->mul(1,3);

$obj->div(4,2);

$obj->add(4,2);

?>


Output

interface-in-php.jpg

© 2013 dotNetheaven. All rights reserved.