In this tutorial, you will learn about the interface, how the interface is implemented in a class, and how it is very helpful for achieving polymorphism in PHP.
Interface An interface is similar to a class except that it cannot contain code.
Using implements
keyword we can cam implement an interface with a Class. An interface can define method names and arguments, but not the contents of the methods
See the below example on Interface.
1 2 3 4 5 | <?php interface OnlineCalculator { public function getArea(); } ?> |
See the below example of how to implement it in a class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php interface OnlineCalculator { public function getArea(); } // Get the Area of a Circle class Circle implements OnlineCalculator { private $radius; public function __construct($radius){ $this -> radius = $radius; } public function getArea(){ return $this -> radius * $this -> radius * pi(); } } $mycircle = new Circle(3); echo $mycircle->getArea(); ?> |
Questions asked by Interview on Interface on PHP
- What is an interface?
- What is the difference between Interface and Abstract Class?
- Which keyword is used for the implementation interface in a class?
Hope this tutorial helps.