Interfaces in php with example

Think of an interface like a class without any behavior or rules to implement.

Interfaces in PHP defines using the interface keyword

interface User{
   // .. Rules
   public function login();
}

we create a user interface with a single method login. now any class implement this interface must declare a login method.

now let's create an Invoice class and implemented User interface

class Invoice implements User{
   public function login(){
      // .. code
   }
}

if you forget to add login method to Invoice class you will get FATEL ERRO

"Fatal error: Class Invoice contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (User::login)"

 

<?php
interface User{
   // .. Rules
   public function login();
}
class Invoice implements User{
   public function login(){
      // .. code
   }
}

Difference between abstract class and interface

Interface

  1. support multiple inheritances
  2. doesn't Contains Data Member
  3. doesn't contains Constructors 
  4. Contains only incomplete member (signature of the member)
  5. cannot have access modifiers by default everything is assumed as public 
  6. Members of the interface can not be Static
  7. Only Complete Member of an abstract class can be Static

Abstract

  1. Can contain access modifiers for the subs, functions, properties
  2. Contains both incomplete (abstract) and complete member
  3. Contains Constructors
  4. Contains Data Member
  5. Doesn't support multiple inheritances