【夯实PHP系列】购物车代码说明PHP的匿名函数

1. 定义:匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。

2. 用法:

  1)作为变量的值

    闭包函数也可以作为变量的值来使用。PHP 会自动把此种表达式转换成内置类 Closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号

  2)从父作用域继承变量

    闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。

  3)一个完整的例子,用购物车代码来说明:

 1 <?php
 2 // 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。
 3 // 其中有一个方法用来计算购物车中所有商品的总价格,该方法使
 4 // 用了一个 closure 作为回调函数。
 5 class Cart
 6 {
 7     const PRICE_BUTTER  = 1.00;
 8     const PRICE_MILK    = 3.00;
 9     const PRICE_EGGS    = 6.95;
10 
11     protected   $products = array();
12     
13     public function add($product, $quantity)
14     {
15         $this->products[$product] = $quantity;
16     }
17     
18     public function getQuantity($product)
19     {
20         return isset($this->products[$product]) ? $this->products[$product] :
21                FALSE;
22     }
23     
24     public function getTotal($tax)
25     {
26         $total = 0.00;
27         
28         $callback =
29             function ($quantity, $product) use ($tax, &$total)
30             {
31                 $pricePerItem = constant(__CLASS__ . "::PRICE_" .
32                     strtoupper($product));
33                 $total += ($pricePerItem * $quantity) * ($tax + 1.0);
34             };
35         
36         array_walk($this->products, $callback);
37         return round($total, 2);;
38     }
39 }
40 
41 $my_cart = new Cart;
42 
43 // 往购物车里添加条目
44 $my_cart->add('butter', 1);
45 $my_cart->add('milk', 3);
46 $my_cart->add('eggs', 6);
47 
48 // 打出出总价格,其中有 5% 的销售税.
49 print $my_cart->getTotal(0.05) . "\n";
50 // 最后结果是 54.29
51 ?>

3. 参考:

  1) php官方说明 '匿名函数':http://www.php.net/manual/zh/functions.anonymous.php

  2)constant() 函数返回一个常量的值: http://www.runoob.com/php/func-misc-constant.html

  3) array_walk() 函数对数组中的每个元素应用用户自定义函数: http://www.w3school.com.cn/php/func_array_walk.asp

  4) round() 函数对浮点数进行四舍五入: http://www.w3school.com.cn/php/func_math_round.asp