1、理解闭包之前先知道一个PHP的array_walk函数
<?php function myfunction($value,$key) { echo "The key $key has the value $value<br>"; } $a=array("a"=>"red","b"=>"green","c"=>"blue"); array_walk($a,"myfunction"); ?> 结果是:(调用了3次myfunction函数) The key a has the value red The key b has the value green The key c has the value blue
<?php 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; $callback = function ($quantity,$product)use ($tax, &$total) { $pricePerItem = constant(__CLASS__ ."::PRICE_" . strtoupper($product)); //其中constant 返回 上边定义常量的值 //跟self::访问一样,self不能再这里使用,所以用上边 $total += ($pricePerItem *$quantity) * ($tax + 1.0); }; array_walk($this->products,$callback); return round($total, 2);; } } $my_cart =new Cart; // 往购物车里添加条目 $my_cart->add('butter', 1); $my_cart->add('milk', 3); $my_cart->add('eggs', 6); // 打出出总价格,其中有 5% 的销售税. print $my_cart->getTotal(0.05) . " "; // The result is 54.29 ?>
&符号则使用变量的地址(传址)