PHP closures using function use

Source: Internet
Author: User

counter

function counter () {
$int = 1;
return function () use (& $int) {echo $int + +;};

}

$count 1 = counter ();
$count 2 = counter ();
$count 1 (); Output 1
$count 2 (); Output 1
$count 1 (); Output 2
$count 2 (); Output 2


Calculate the amount of the shopping cart, tax
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 "Product:". $goods _name;
echo "Quantity:". $num;
$goods _amt_tax = Bcmul ($price, $num, 2);
$goods _price = Round (Bcdiv ($price, Bcadd ($taxRate, 1, 2), 12), 6);
echo "Unit Price:". $goods _price;
$goods _amt = Round (Bcmul ($goods _price, $num, 6), 2);
echo "Amount:". $goods _amt;
$goods _tax = bcsub ($goods _amt_tax, $goods _amt, 2);
echo "Tax:" $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 "Total amount:". $amt _price. "\ n";
echo "Total tax:". $amt _tax. "\ n";
echo "Gold tax total:". $amt. "\ n";
}
$cart = Array ("Apple" =>array ("=>20", "num" =>1), "Orange" =>array ("Price" =>15, "num" =>2));
Calculate ($cart);

The above describes the PHP closure using function use, including the contents of the counter, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.