Skip to content

Instantly share code, notes, and snippets.

@ftdebugger
Last active December 18, 2015 16:39
Show Gist options
  • Save ftdebugger/5812959 to your computer and use it in GitHub Desktop.
Save ftdebugger/5812959 to your computer and use it in GitHub Desktop.
<?php
/**
* @author Evgeny Shpilevsky <evgeny@shpilevsky.com>
*/
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