【夯實PHP系列】購物車代碼說明PHP的匿名函數

來源:互聯網
上載者:User

標籤:

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的匿名函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.