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.