Interfaces in PHP


Interfaces in php:


An Interface does not contain any functionality, it only specify set of methods which classes must implement.

You can create interface in php oop by using interface keyword.

An Interface is like a template similar to abstract class but there are little bit differences where you can use only abstract methods

You can implement your interface in classes by using implements keyword.

You will have to notice that when you are going to implement interface in your class then method should be define with public accessibility.

If you will use other than public visibility then it will generate error.

Interface are a good way to implement reusability. you can define interface for a number of condition, you can then implement your interface in different ways.

Problem of multiple inheritance can be resolved by using interface.

Note :  While defining method in your interface, do not use abstract keyword in your methods.

Example:

interface a

{

 public function abc();

}

interface b extends a

{

 public function xyz(Xyz $xyz);

}

// This will work

class c implements b

{

 public function abc()

 {

 }

 public function xyz(Xyz $xyz)

 {

 }

}

// This will not work and result in a fatal error

class d implements b

{

 public function abc()

 {

 }

 public function xyz(Abc $abc)

 {

 }

}


 Output: Fatal error: Declaration of d::xyz() must be compatible with that of b::xyz() in C:\wamp\www\webpage\multipleinterface.php on line 20.

Custom Search

%d bloggers like this: