What are PHP interfaces and how to use them

What are PHP interfaces and how to use them?

What are the PHP interfaces?

A PHP interface is a collection of declared methods, and when a class implements an interface the class must define the declared methods of the interface.

Rules of PHP Interfaces

  • You cannot create objects of interfaces like abstract classes.
  • You cannot create properties inside an interface. Only methods are allowed to be declared.
  • All the methods of an interface must be public, and you cannot change the access modifier even while defining the methods.

How to create PHP interfaces?

The interface keyword is used to create a PHP interface.

interface InterfaceName{
    // Declaration of Functions
}
interface SayHello{
    function hello();
}

How to use the interfaces?

Use the implements keyword to implement the interfaces to a Class.

<?php
interface SayHello{
    function hello($name);
}

class MyClass implements SayHello{
    function hello($name){
        echo "Hello $name!";
    }
}

$obj = new MyClass();
$obj->hello("John");
Hello John!

Implement multiple interfaces to a class

Yes! you can implement multiple interfaces to a class. Let’s see how to do this –

<?php
interface SayHello{
    function hello($name);
}

interface SayHi{
    function hi($name);
}

class MyClass implements SayHello, SayHi{
    function hello($name){
        echo "Hello $name!\n";
    }

    function hi($name){
        echo "Hi $name!";
    }
}

$obj = new MyClass();
$obj->hello("John");
$obj->hi("Mark");
Hello John!
Hi Mark!