PHP 闭包使用

function printStr() {
    $str = 1;
    return function()use(&$str){echo $str++;};
}



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";
}

你可能感兴趣的:(php)