This article mainly talks about six tips for using anonymous functions. It has certain learning value. Interested friends can learn it.
I have written an article about the use of closures before (click here to enter). This time I will give an in-depth summary of the in-depth usage and understanding of anonymous functions in PHP:
Anonymous functions in PHP are also called Closure functions allow specifying a function without a name. Assign the anonymous function to a variable and call it through the variable. Here is a simple example:
Copy after login
Tip 1:Put the anonymous function in a normal function, or you can return the anonymous function. : This forms a simple closure
Copy after login
Tip 2Reference local variables in anonymous functions (here you need to quote a php keyword use)
Copy after login
Tip 3Return an anonymous function in a normal function
Copy after login
Tip 4Return an anonymous function and pass parameters to the anonymous function
Copy after login
Tips 5Use closure to change the variable value referenced by the context
Copy after login
Based on the above input results, it is found that the following two func() both return 101 and the value has not changed. If you want to accumulate the effect, just add An & reference symbol is enough (modifications within the anonymous function will also affect external variables), modify it:
Copy after login
Tip 6Pass the anonymous function as a parameter
Copy after login
Related tutorials:PHP video tutorial
The above is the detailed content of [PHP Learning] Six tips for using anonymous functions. For more information, please follow other related articles on the PHP Chinese website!