Interface
➔ Interface in object oriented is a template, which allows us to create a framework for one or more objects
➔ Looking at the interface, we can completely determine which methods and fixed attributes (or constants) are present in the object that implements it.
➔ Syntax:
1 2 3 4 5 6 7 | <?php Interface InterfaceName { // code to do } ?> |
Interface properties
➔ Interface is not an object
➔ In the interface we are only declaring methods, not defining them.
◆ In the interface we can declare a constant but can not declare the variable.
◆ An interface can not be initialized (because it is not an object).
◆ Implement interface classes must declare and redefine the methods contained in that interface.
◆ A class can implement multiple interfaces.
◆ Interfaces can inherit each other.
Use Interface
➔ Create interface
➔ Create class implements interface
➔ The class defines the contents of the functions
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php interface Animal { public function getName(); } { private $name; public function getName() { return $this->name; } } ?> |
Use Interface
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php interface Animal { public function getName(); } interface Buffalo { public function checkHorn(); } public class TheCalf implements Animal, Buffalo { private $name; const HORN = false; public function getName() { return $this->name; } public function checkHorn() { return self::HORN; } } ?> |
Use Interface
➔ Create interface
➔ Create interface inheritance interface
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php interface Animal { public function getName(); } interface Buffalo extends Animal { public function checkHorn(); } public class TheCalf implements Buffalo { private $name; const HORN = false; public function getName() { return $this->name; } public function checkHorn() { return self::HORN; } } ?> |