Friday 5 April 2019

Interface in PHP

Interfaces - the next level of abstraction


The interface blocks which declares set of functions to be defined with a class to implement this interface.
A class can extend more than one interface.


Declare and implement an interface?
We declare an interface with the interface keyword and, a class that inherits from an interface with the implements keyword.

interface interfaceName { 
  // abstract methods
}

class Child implements interfaceName {
  // defines the interface methods and may have its own code
}

Example:  Create an interface for the classes that handle cars, which commits all its child classes to setModel() and getModel() methods.

interface Car { 
  public function setModel($name);
  
  public function getModel();
}

Interfaces can have only public methods and cannot have variables. Methods in interfaces don't have body.

The classes that implement the interfaces must define all the methods that they inherit from the interfaces, including all the parameters. So, in our concrete class with the name of miniCar, we add the code to all the abstract methods.

class miniCar implements Car {
  private $model; 
   
  public function setModel($name) 
    $this -> model = $name; 
  }
  
  public function getModel() {
    return $this -> model; 
  }
}

Implement more than one interface in the same class?
We can implement a number of interfaces in the same class.

In order to demonstrate multiple inheritance from different interfaces, we create another interface, Vehicle, that commits the classes that implement it to a boolean $hasWheels property.

interface Vehicle {
  public function setHasWheels($bool); 

  public function getHasWheels();
}

Now, our child class can implement the two interfaces.

class miniCar implements Car, Vehicle {
  private $model; 
  private $hasWheels; 
  
  public function setModel($name) 
    $this -> model = $name; 
  }
  
  public function getModel() {
    return $this -> model; 
  }
  
  public function setHasWheels($bool) 
    $this -> hasWheels = $bool; 
  }
  
  public function getHasWheels() {
    return ($this -> hasWheels)? "has wheels" : "no wheels";
  }
}


Differences between abstract classes and interfaces?

Interface supports multiple inheritance while abstract class doesn't support multiple inheritance
Interface doesn't contain constructors while abstract class contains constructors.
Interface contains only incomplete member(signature of member) while abstract class contains both incomplete(abstract) and complete member.
Interface cannot have access modifiers by default everything is assumed as public while abstract class can contain access modifiers for the subs, functions, properties.
Members of interface cannot be static while only complete member of abstract class can be static.

No comments:

Post a Comment