//计数器
function counter() {
$int = 1;
return function()use(&$int){echo $int++;};
}
$count1 = counter();
$count2 = counter();
$count1(); //output 1
$count2(); //output 1
$count1(); //output 2
$count2(); //output 2
//计算购物车的金额、税额
function calculate($cart = array()) {
$amt = 0;
$amt_tax = 0;
$amt_price = 0;
$taxRate = 0.17;
$callback = function($goods_info, $goods_name) use (&$amt, &$amt_tax, &$amt_price, $taxRate) {
extract($goods_info);
echo " 商品: ". $goods_name;
echo " 数量:".$num;
$goods_amt_tax = bcmul($price, $num, 2);
$goods_price = round(bcdiv($price, bcadd($taxRate, 1, 2), 12), 6);
echo " 单价:".$goods_price;
$goods_amt = round(bcmul($goods_price, $num, 6), 2);
echo " 金额:".$goods_amt;
$goods_tax = bcsub($goods_amt_tax, $goods_amt, 2);
echo " 税额:".$goods_tax. "\n";
$amt = bcadd($amt, $goods_amt_tax, 2);
$amt_tax = bcadd($amt_tax, $goods_tax, 2);
$amt_price = bcadd($amt_price, $goods_amt, 2);
};
array_walk($cart, $callback);
echo "合计金额:". $amt_price. "\n";
echo "合计税额:". $amt_tax. "\n";
echo "金税合计:". $amt. "\n";
}
$cart = array("apple"=>array("price"=>20, "num"=>1), "orange"=>array("price"=>15, "num"=>2));
calculate($cart);