標籤:
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.2951 ?>
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
【夯實PHP系列】購物車代碼說明PHP的匿名函數