1. definition : An anonymous function (Anonymous functions), also called a closure function (closures), allows temporary creation of a function without a specified name. The value most often used as the callback function (callback) parameter. Of course, there are other applications as well.
2. Usage :
1) as the value of the variable :
The closure function can also be used as the value of a variable. PHP automatically converts this expression into an object instance of the built-in class Closure. Assigning a closure object to a variable is the same as the syntax for assigning a value to a normal variable, with a semicolon at the end.
2) inherit the variable from the parent scope :
Closures can inherit variables from the parent scope. Any such variables should be passed in using the use language structure.
3) A complete example, using the shopping Cart code to illustrate:
1<?PHP2 //a basic shopping cart, including some already added items and the quantity of each item. 3 //There is a method for calculating the total price of all items in the shopping cart, which makes4 //Use a closure as the callback function. 5 classCart6 {7 ConstPrice_butter = 1.00;8 ConstPrice_milk = 3.00;9 ConstPrice_eggs = 6.95;Ten One protected $products=Array(); A - Public functionAdd$product,$quantity) - { the $this->products[$product] =$quantity; - } - - Public functionGetquantity ($product) + { - return isset($this->products[$product]) ?$this->products[$product] : + FALSE; A } at - Public functionGettotal ($tax) - { - $total= 0.00; - - $callback= in function($quantity,$product) Use($tax, &$total) - { to $pricePerItem=constant(__class__. "::P rice_". + Strtoupper($product)); - $total+= ($pricePerItem*$quantity) * ($tax+ 1.0); the }; * $ Array_walk($this->products,$callback);Panax Notoginseng return round($total, 2);; - } the } + A $my _cart=NewCart; the + //Add items to your shopping cart - $my _cart->add (' Butter ', 1); $ $my _cart->add (' Milk ', 3); $ $my _cart->add (' Eggs ', 6); - - //Hit the total Price, which has a sales tax of 5%. the Print $my _cart->gettotal (0.05). "\ n"; - //and The final result is 54.29 .Wuyi?>
3. Reference :
1) PHP official description ' anonymous function ': http://www.php.net/manual/zh/functions.anonymous.php
2) Theconstant() function returns the value of a constant: http://www.runoob.com/php/func-misc-constant.html
3) the Array_walk () function applies the user-defined function to each element in the array: http://www.w3school.com.cn/php/func_array_walk.asp
4) the round () function rounds the floating-point number: http://www.w3school.com.cn/php/func_math_round.asp
"tamping PHP series" Shopping Cart code description PHP anonymous function