Create and Using an Interface in PHP
Description
The following code shows how to create and Using an Interface.
Example
<?php/*from w w w . j a va 2 s. co m*/
interface Sellable {
public function addStock( $numItems );
public function sellItem();
public function getStockLevel();
}
class Tablet implements Sellable {
private $_screenSize;
private $_stockLevel;
public function getScreenSize() {
return $this->_screenSize;
}
public function setScreenSize( $screenSize ) {
$this->_screenSize = $screenSize;
}
public function addStock( $numItems ) {
$this->_stockLevel += $numItems;
}
public function sellItem() {
if ( $this->_stockLevel > 0 ) {
$this->_stockLevel--;
return true;
} else {
return false;
}
}
public function getStockLevel() {
return $this->_stockLevel;
}
}
class Meat implements Sellable {
private $_color;
private $_ballsLeft;
public function getColor() {
return $this->_color;
}
public function setColor( $color ) {
$this->_color = $color;
}
public function addStock( $numItems ) {
$this->_ballsLeft += $numItems;
}
public function sellItem() {
if ( $this->_ballsLeft > 0 ) {
$this->_ballsLeft--;
return true;
} else {
return false;
}
}
public function getStockLevel() {
return $this->_ballsLeft;
}
}
class StoreManager {
private $_productList = array();
public function addProduct( Sellable $product ) {
$this->_productList[] = $product;
}
public function stockUp() {
foreach ( $this->_productList as $product ) {
$product->addStock( 100 );
}
}
}
$tv = new Tablet;
$tv->setScreenSize( 42 );
$ball = new Meat;
$ball->setColor( "yellow" );
$manager = new StoreManager();
$manager->addProduct( $tv );
$manager->addProduct( $ball );
$manager->stockUp();
echo "<p>There are ". $tv->getStockLevel() . " " . $tv->getScreenSize();
echo "-inch Tablets and " . $ball->getStockLevel() . " " . $ball->getColor();
echo ".</p>";
$tv->sellItem();
$ball->sellItem();
$ball->sellItem();
echo $tv->getStockLevel() . " " . $tv->getScreenSize(). " ";
echo $ball->getStockLevel() . " " . $ball->getColor();
?>
The code above generates the following result.