Last active
December 18, 2015 16:39
-
-
Save ftdebugger/5812959 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Evgeny Shpilevsky <[email protected]> | |
*/ | |
class Purchase | |
{ | |
/** | |
* @var int | |
*/ | |
protected $cost; | |
/** | |
* @param int $cost | |
*/ | |
public function __construct($cost) | |
{ | |
$this->cost = $cost; | |
} | |
/** | |
* @return int | |
*/ | |
public function getCost() | |
{ | |
return $this->cost; | |
} | |
} | |
class Cart implements IteratorAggregate | |
{ | |
/** | |
* @var Purchase[] | |
*/ | |
protected $purchases; | |
/** | |
* @param Purchase $purchase | |
*/ | |
public function addPurchase(Purchase $purchase) | |
{ | |
$this->purchases[] = $purchase; | |
} | |
/** | |
* @return int | |
*/ | |
public function getCost() | |
{ | |
$cost = 0; | |
foreach ($this->purchases as $purchase) { | |
$cost += $purchase->getCost(); | |
} | |
return $cost; | |
} | |
/** | |
* @return ArrayIterator|Traversable | |
*/ | |
public function getIterator() | |
{ | |
return new ArrayIterator($this->purchases); | |
} | |
} | |
$cart = new Cart(); | |
$cart->addPurchase(new Purchase(10)); | |
$cart->addPurchase(new Purchase(15)); | |
var_dump($cart->getCost()); // 25 | |
foreach($cart as $purchase) { | |
var_dump($purchase->getCost()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment