PHP Interface

You can use interfaces to describe which methods a class should implement.

An interface does not contain abstract methods; instead, it has public methods without any definition, and classes inheriting the interface must define the methods declared within the interface class.

The interface keyword is used to declare interfaces:

Interfaces Syntax:

<?php
    // interface declaration
    interface NameOfInterface {
        public function someMethod();
    }
    
?>

The implements keyword allows a class to inherit from an interface and then define the interface’s methods.The class which implements an interface is called the Concrete Class.

All of the methods of an interface must be implemented by a class that implements it.

<?php
    // class declaration
    class SomeClass implements NameOfInterface {
        // define the intrface class declared methods
    }
    
?>

Consider the following scenario: we build an interface with some methods declared in it, and the class that implements it is bound to provide a definition for those methods.

<?php
   interface data{
      public function printData();
       public function getData();
   }
   class d implements data
   {
         public function getData()
         {
         echo "I am reading data";
        }
       public function printData()
       {
         echo "I am printing<br>";

       }
   }
   $myobj = new d();
   $myobj->printData();
   $myobj->getData();
?>

The following are some of the properties of an interface:

  • An interface is made up of methods that don’t have definition, hence they are called abstract methods.
  • All of the interface methods are public and do not begin with the abstract keyword.
  •  An error will occur,  if we fail to implement even a single method declared in the interface in the class that implements the interface.
  • Although a class can inherit from only one other class, but it can implement one or more interfaces.
  • There can not be any variables inside the interface.

Note: Because a class can implement many interfaces but only extend one class, we can achieve multiple inheritance via interfaces.