PHP 购物车 php闭包 array_walk
2016-03-23 18:24
281 查看
<?php class Cart { const PRICE_BUTTER = 1.00; const PRICE_MILK = 3.00; const PRICE_EGGS = 6.95; protected $products = array(); public function add($product, $quantity) { $this->products[$product] = $quantity; } public function getQuantity($product) { return isset($this->products[$product]) ? $this->products[$product] : FALSE; } public function getTotal($tax) { $total = 0.00; $callback = function ($quantity, $product) use ($tax, &$total) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); }; array_walk($this->products, $callback); return round($total, 2);; } } $my_cart = new Cart; // 往购物车里添加条目 $my_cart->add('butter', 1); $my_cart->add('milk', 3); $my_cart->add('eggs', 6); print $my_cart->getQuantity('milk'); echo "<br/>"; // 打出出总价格,其中有 5% 的销售税. print $my_cart->getTotal(0.05) . "\n"; // 最后结果是 54.29 ?>
相关文章推荐
- Scala、PHP、Golang 二分法查找
- yii2实现数据分页显示
- 文件传输导致PHP-smarty白屏故障
- PHP核心技术与最佳实践——总结
- Setting下增加触摸笔功能(TP)
- Thinkphp3.2.3 解决关联模型的自动生成问题($_auto)
- Yii2 表单
- windows环境phpstorm调试环境搭建
- laravel 5.2 form模块调用时出错
- yii2 邮件发送
- PHP并发IO编程之路
- 浅谈PHP类与对象
- 利用Angular.js从PHP读取后台数据
- Ubuntu 14.04 vsftp refusing to run with writable root inside chroot问题解决方法
- PHP 网页保存为Word文档
- PHP输出Excel两种方法
- PHP 底层的运行机制与原理
- PHP extract() 函数
- 安装 Laravel 出问题了?你可能需要修改 composer.json 文件
- php phpExcel