php闭包函数得参数传递与注释

<?php 
// 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。 
// 其中有一个方法用来计算购物车中所有商品的总价格。该方法使用了一个closure作为回调函数。 
class Cart 

const PRICE_BUTTER = 1.00; //产品对应价格
const PRICE_MILK = 3.00; //产品对应价格
const PRICE_EGGS = 6.95; //产品对应价格


protected $products =array(); 


public function add($product,$quantity) 

$this->products[$product] = $quantity; 



public function getQuantity($product) 

return isset($this->products[$product]) ? $this->products[$product] : 
FALSE; 



public function getTotal($tax) //获取价格

$total = 0.00; 
//自定义函数结合下面使用,function得参数是产品数组得数量和key,
//use数组引用得外部一个销售税参数,一个要返回存储价格得变量,价格变量使用&引用传递函数内可以修改此变量得值,必须用引用传递
$callback = function ($quantity,$product)use ($tax, &$total) 

$pricePerItem = constant(__CLASS__ ."::PRICE_" . strtoupper($product)); //把传入参数改为大写,返回常量得值,取得是价格参数PRICE_BUTTER/PRICE_MILK/PRICE_EGGS
$total += ($pricePerItem *$quantity) * ($tax + 1.0); //当前价格X数量X消费税,赋值给引用传递得外部变量值
}; 


array_walk($this->products,$callback); //当前产品数组,调用自定义函数第一个参数是产品数组,第二个参数是自定义函数
return round($total, 2);//对浮点数取整,保留两位,抛出变量




$my_cart =new Cart; //实例化类


// 往购物车里添加条目 
$my_cart->add('butter', 1); //购买得产品与数量,传入参数写入$products
$my_cart->add('milk', 3); //购买得产品与数量,传入参数写入$products
$my_cart->add('eggs', 6); //购买得产品与数量,传入参数写入$products


// 打出出总价格,其中有 5% 的销售税. 
print $my_cart->getTotal(0.05) . "\n"; //调用函数
// The result is 54.29 
?>

猜你喜欢

转载自blog.csdn.net/sn_qmzm521/article/details/80938541