PHP 閉包使用 function use

來源:互聯網
上載者:User

//計數器

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教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.