Use of PHP closure functions
# Use of the PHP closure function anonymous function is also called the closure function (closures allows you to create a function that is not specified and is most often used as the value of the callback function parameter. _ Closure function _ no function name. when function () is passed in to a variable, the defined variable is treated as a function. "$ cl = function ($ name) {return sprintf ('HELLO % s', name);} echo $ cli ('fuck ') '"calls echo preg_replace_callback ('~ -([A-z]) ~ ', Function ($ match) {return strtoupper ($ match [1]) ;}, 'Hello-world '); "'### use" $ message = 'hello'; $ example = function () use ($ message) {var_dump ($ message );}; echo $ example (); // output hello $ message = 'world '; // output hello because the value of the inherited variable is defined by the function instead of echo $ example () when the function is called; // reset to hello $ message = 'hello '; // Here $ example = function () use (& $ message) {var_dump ($ message) ;}; echo $ example (); // output hello $ message = 'world'; ec Ho $ example (); // The output world // closure function is also used for normal value transfer $ message = 'hello'; $ example = function ($ data) use ($ message) {return "{$ data}, {$ message}" ;}; echo $ example ('world '); "### example" class Cart {// define constants in the class using the const keyword instead of the general define () function. Const PRICE_BUTTER = 1.00; const PRICE_MILK = 3.00; const PRICE_EGGS = 6.95; protected $ products = []; public function add ($ product, $ quantity) {$ this-> products [$ product] = $ quantity;} public function getQuantity ($ product) {// is return isset ($ this-> products [$ product]) defined? $ This-> products [$ product]: FALSE;} public function getTotal ($ tax) {$ total = 0.0; $ callback = function ($ quantity, $ product) use ($ tax, & $ total) {// constant returns the constant value // _ class _ returns the CLASS name $ price = constant (_ class __. ": PRICE _". strtoupper ($ product); $ total + = ($ price * $ quantity) * ($ tax + 1.0) ;}; // array_walk () the function applies user-defined functions to each element in the array. In the function, the key and key values of the array are the parameter array_walk ($ this-> products, $ callback); // callback anonymous function return round ($ total, 2 );}} $ my_cart = new Cart (); $ my_cart-> add ('butter ', 1); $ my_cart-> add ('milk', 3 ); $ my_cart-> add ('eggs', 6); print ($ my_cart-> getTotal (0.05 ));"