Skip to content

Instantly share code, notes, and snippets.

@grim-reapper
Last active August 29, 2015 14:06
Show Gist options
  • Save grim-reapper/3459c0bc1558c6f4c6cc to your computer and use it in GitHub Desktop.
Save grim-reapper/3459c0bc1558c6f4c6cc to your computer and use it in GitHub Desktop.
PHP: Cart Class with Anonymous function
<?php
/**
* MIT License
* ===========
*
* Copyright (c) 2012 MindCracker <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @category PHP
* @package Cart Class
* @subpackage none
* @author MindCracker <[email protected]>
* @copyright 2012 MindCracker.
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @version 1.0
* @link http://smartweb.webz2feel.com
*/
class Cart
{
const PRICE_BUTTER = 1.00;
const PRICE_MILK = 3.00;
const PRICE_EGGS = 6.85;
public $_products = array();
public function add($product,$quantity)
{
$this->_products[$product] = $quantity;
}
public function getQuanitity($product)
{
return isset($this->_products[$product]) ? $this->_products[$product] : false;
}
public function getTotal($tax)
{
$total = 0.00;
$calback = function ($quantity,$product) use($tax, &$total)
{
$pricePetItem = constant(__CLASS__."::PRICE_".strtoupper($product));
$total += ($pricePetItem * $quantity) * ($tax + 1.0);
};
array_walk($this->_products, $calback);
return round($total,2);
}
}
$my_cart = new Cart;
$my_cart->add('butter',1);
$my_cart->add('milk',3);
$my_cart->add('eggs',6);
echo $my_cart->getTotal(0.05);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment