PHP匿名函數(閉包)

來源:互聯網
上載者:User
匿名函數(Anonymous functions),也叫閉包函數(closures),允許 臨時建立一個沒有指定名稱的函數。最經常用作回呼函數(callback)參數的值。當然,也有其它應用的情況。

結合array_walk和匿名函數來實現一個結算功能

array_walk() 函數對數組中的每個元素應用回呼函數。如果成功則返回 TRUE,否則返回 FALSE。

 1 _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用於返回字串形式常量的值

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.