+

When do we need interfaces in PHP?

Example : interface man { // List of public methods 
}
Interfaces can contain methods and / or constants, but no attributes. Interface constants have the same restrictions as class constants. Interface methods are implicitly abstract.Example : interface IMyInterface { const INTERFACE_CONST_1 = 1; const INTERFACE_CONST_2 = `a string` ; public function method_1(); public function method_2(); }
?>
Any class that needs to implement an interface must use the keyword Implements. One class can implement more than one interface at a time. // Function for multiple elements
/ / interface one class at a time. class MyClass implements IMyInterface { public function method_1() { // implementation_1 method } public function method_2() {< / code> // method_2 implementation } }< / strong>Interesting points:
  • A class cannot implement two interfaces that have the same method name, because that would result in method ambiguity.
  • Like classes, you can establish inheritance relationships between interfaces using the same "extends" keyword. 
    Example : interface Foo { 
    } interface Bar {  
    } interface Bass extends Foo, Bar {  
    }
Below is a complete example that shows how interfaces work. 
Example :  
// PHP program to implement the interface. 
// Define a new interface for all "shapes"
// inherit interface Shape { // Define methods required for // classes to implement public function getColor(); public function setColor ( $color ); // Interfaces cannot define generic // functions, so we`ll just define // method for all implementations // define public function describe(); }  
// Define a new Triangle class that
// inherits from the Shape interface class Triangle implements Shape { private $color = null; // Define the required methods // in the abstract class ` Shape ` public function getColor() { return $this -> color; } public function setColor ( $color ) {< p> $this -> color = $color ; } public function describe() { return sprintf ( "GeeksforGeeks% s% s" , $this -> getColor(), get_class (< / code> $this )); } } $triangle = new Triangle();  
// Set color $triangle -> setColor ( `green` );  
// Print the value of the general description
// method provided by the abstract class
// print "I`m an orange triangle" print $triangle -> describe(); ?>
Output:
 GeeksforGeeks green Triangle 
Importance of using interfaces:
  • An interface provides a flexible base / root structure that you don`t get with classes.
  • When implementing an interface, the caller should only care about the object`s interface, not the implementation of the object`s methods.
  • An interface allows unrelated classes to implement the same set of methods regardless of their position in the hierarchy class inheritance.
  • The interface allows you to model multiple inheritance.
Get Solution for free from DataCamp guru