Implementing interfaces is a way of creating a set of methods that people must implement if they want to be viewed as a member of the class of objects with the same interface. You declare an interface with the interface
keyword:
<?php // prefixing the interface name with a capital I is // strictly a naming convention that I use. interface IProduct { public function get_ProductID(); public function get_ProductName(); public function setPrice($price); } interface IBuyer { public function get_BuyerID(); public function get_BuyerName(); }
Classes indicate that they want to implement an interface by using the implements
keyword:
<?php class Product implements IProduct { private $productID; private $productName; protected $productPrice; public function __construct($pid, $pn) { $this->productID = $pid; $this->productName = $pn; } public function get_ProductID(){ return $this->productID; } public function get_ProductName(){ return $this->productName; } public function setPrice($price){ $this->productPrice = $price; } }
1. A class can implement multiple interfaces:
<?php class Product implements IProduct, IBuyer { // implement all methods declared in // IProduct and IBuyer interfaces ... }
2. An abstract class can implement interfaces:
<?php abstract class Product implements IProduct, IBuyer { // ... }
3. A class can extend its parent class and implement interfaces at the same time:
<?php class Product extends Pproduct implements IProduct { // ... }
4. Abstract, Extends, and Implements all together:
<?php abstract class Product extends Pproduct implements IProduct { // your code }
PHP OOP Tutorials: