Advertisement
zukars3

Untitled

Mar 28th, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.15 KB | None | 0 0
  1. <?php
  2.  
  3. interface ShopInterface
  4. {
  5.     public function getTotalPrice(): float;
  6. }
  7.  
  8. interface ProductInterface
  9. {
  10.     public function getPrice(): float;
  11. }
  12.  
  13. class Shop implements ShopInterface
  14. {
  15.     private $products;
  16.  
  17.     public function __construct(array $products = [])
  18.     {
  19.         $this->products = $products;
  20.     }
  21.  
  22.     public function setProducts(ProductInterface $product): void
  23.     {
  24.         $this->products[] = $product;
  25.     }
  26.  
  27.     public function getTotalPrice(): float
  28.     {
  29.         $totalPrice = 0;
  30.  
  31.         foreach ($this->products as $product) {
  32.             $totalPrice += $product->getPrice();
  33.         }
  34.  
  35.         return $totalPrice;
  36.     }
  37. }
  38.  
  39. class Product implements ProductInterface
  40. {
  41.     private $price;
  42.  
  43.     public function __construct(float $price)
  44.     {
  45.         $this->price = $price;
  46.     }
  47.  
  48.     public function getPrice(): float
  49.     {
  50.         return $this->price;
  51.     }
  52.  
  53. }
  54.  
  55. $apple = new Product(1.99);
  56. $banana = new Product(2.99);
  57. $lemon = new Product(3.99);
  58.  
  59. $shop = new Shop();
  60. $shop->setProducts($apple);
  61. $shop->setProducts($banana);
  62. $shop->setProducts($lemon);
  63. echo $shop->getTotalPrice() . PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement