欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP 闭包使用 function use

程序员文章站 2024-01-03 22:39:46
...

//计数器

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);

以上就介绍了PHP 闭包使用 function use,包括了计数器方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

上一篇:

下一篇: