匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。
结合array_walk和匿名函数来实现一个结算功能
array_walk() 函数对数组中的每个元素应用回调函数。如果成功则返回 TRUE,否则返回 FALSE。
1 <?php 2 class anyMouseTest{ 3 //定义商品类型、价格 4 const IPHONE6_PRICE = 5500; 5 const XIAOMI4_PRICE = 1999; 6 const HONERX_PRICE = 799; 7 8 private $_productSort; 9 private $_products; 10 11 public function __construct(){ 12 $this->_productSort = array('iphone6','xiaomi4','honerx'); 13 $this->_products = array(); 14 } 15 16 public function addProduct($product , $sum){ 17 if(in_array($product , $this->_productSort) && is_int($sum)){ 18 $this->_products[$product] = $sum; 19 } 20 } 21 22 public function getCount($tax){ 23 $count = 0; 24 25 $callback = function($sum , $product) use ($tax , &$count){ 26 $price = constant(__CLASS__.'::'.strtoupper($product).'_PRICE'); 27 $curPrice = $price* $sum * $tax; 28 $count += $curPrice; 29 }; 30 31 array_walk($this->_products, $callback); 32 return $count; 33 } 34 } 35 36 $oanyMouse = new anyMouseTest; 37 38 $oanyMouse->addProduct('iphone6',1); 39 $oanyMouse->addProduct('honerx',2); 40 echo $oanyMouse->getCount(1);
其中constant用于返回字符串形式常量的值