Interface in OOP PHP

In this tutorial we will discuss Interface in OOP PHP. Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined. To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

You can only define method in interface with public accessibility. If you will use other than public visibility in interface then it will throw error. Also while defining method in your interface do not use abstract keyword in your methods.
You can also extend interface like class. You can extend interface in php using extends.

Example:

interface template1
{
public function function1();
}
interface template2 extends template1
{
public function function2();
}
class abc implements template2
{
public function function1()
{
//Your function body
}
public function function2()
{
//your function body
}
}

So here template2 has all property of tempate2. So whenever you will implement template2 in your class, you have to create function of both interfaces.You can also extend multiple interface in one interface in php. You can also implement more than one interface in php class.

Example:

interface a
{
    public function foo();
}

interface b
{
    public function bar();
}

interface c extends a, b
{
    public function baz();
}

class d implements c
{
    public function foo()
    {
    }

    public function bar()
    {
    }

    public function baz()
    {
    }
}

Important

You can not implement 2 interfaces if both share function with same name. It will throw error.Your function parameter in class must be identical to the parameter in the interface signature.But it is not necessary to use the same name of the variable. Like $a. You can also use any $x in the second variable for the same function.

For more Read OOP in PHP