: This article mainly introduces PHP closure functions. For more information about PHP tutorials, see. An anonymous function is also called a closure function (closures allows you to create a function that is not specified and is most often used as the value of a callback function parameter.
The closure function does not have a 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')`
You can call this function directly by defining it as the name of an anonymous function variable.
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'; // Reference $ example = function () use (& $ message) {var_dump ($ message);} here );}; echo $ example (); // output hello $ message = 'world'; echo $ example (); // output the 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, rather than the usual 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 ));
The above is related to the PHP closure function, and I hope it will help you learn it.
The above introduces the PHP closure function details, including the content, hope to be helpful to friends who are interested in the PHP Tutorial.