Interface In PHP

What is Interface?

Interface in oop enforce definition of some set of method in the class. By implementing interface you are forcing any class to must declaring some specific set of methods in oop. For example if you are creating class to render HTML element then it is necessary to set id and name of your html tag. So in this case you will create interface for that class and define method like setID and setName. So whenever someone will create any class to render HTML tag and implemented your interface then he must need to define setId and setName method in their class. In other word you can say that by help of interface you can set some definition of your object. Interface is very useful if you are creating architecture of any oop base application. Inter

Interface in PHP

Interface in php can be implemented like other oop lanugage. You can create interface in php using keyword interface. By implementation of interface in php class you are specifying set of the method which classes must implement.

You can create an interface in PHP using interface keyword. Rest of the things are typically identical to classes. Following is a very small example of an interface in PHP.

interface abc
{
public function xyz($b);
}

So in above code, you are creating an interface with name abc. Interface abc has function xyz. Whenever you will implement the abc interface in your class then you have to create a method with the name xyz. If you will not create function xyz then it will throw an error.

You can implement your interface in your class using implements keyword. Let us implement our interface abc in our class

class test implements abc
{
public function xyz($b)
{
//your function body
}
}

You can only define a method in the interface with public accessibility. If you will use other than public visibility in the interface then it will throw an error. Also while defining method in your interface does not use the abstract keyword in your methods.

Leave a Reply