Php, function: use anonymous functions in php: old rules, first go to the code and then talk .;} FunctionshowObj ($ obj) {echo $ obj.;} mswap imports the reference type. Functionmsw old rules, first on the code to speak.
";} Function showObj ($ obj) {echo $ obj." ";}// mswap imports the reference type. Function mswap (& $ a, & $ B) {$ tmp = $ a; $ a = $ B; $ B = $ tmp;} function bubbleSort (& $ cols) {$ len = count ($ cols); for ($ I = 0; $ I <$ len; $ I ++) {for ($ j = 1; $ j <$ len-$ I; $ j ++) {if ($ cols [$ j-1]> $ cols [$ j]) {mswap ($ cols [$ j-1], $ cols [$ j]) ;}}}$ data = array (8, 2, 3, 9, 0, 45, 35,235); // sort bubbleSort ($ data); // Print the array showArray ($ data); // use the callback function to traverse and print the array array_map ('showobj ', $ data); echo"
"; // Use an anonymous function to traverse and print the array array_map (create_function ('$ obj', 'echo $ obj." "; '), $ data) in sequence;?>
Program output:
The function of the code is very simple. initialize an array, sort it, and print it out in three different ways.
The sorting algorithm uses the simplest bubble sorting.
Note the following:
(1) Both the sorting and switching functions use the method for transferring references. If the value passing method is used, the sorting and switching functions do not take effect, because at this time, the function actually operates on copying parameter objects.
(2) array_map comes with php, and its function is to call the passed functions for each object in the array in sequence. This method is called callback.
(3) create_function can create an anonymous function. In the last print example, the created anonymous function is used as the array_map parameter.
Actually, experienced programmers know that anonymous functions are inefficient in both C ++ 11 and php. So why do I need to use anonymous functions? Why does the new C # and java standards support it?
Although a famous function looks intuitive, there is a cost for management. If there is one more function, there is one more place to manage. In addition, for a "micro" code segment, writing a famous function for it alone also seems that the code is not compact enough. However, this does not mean that anonymous functions can be abused. when the code segment is too large, using anonymous functions will seriously damage readability. The usage of anonymous functions depends on the situation.
The above describes how to use anonymous functions in php, including php and functions. I hope my friends who are interested in PHP tutorials will be helpful.