[PHP Learning] Six tips for using anonymous functions

little bottle
Release: 2023-04-06 09:32:02
forward
2372 people have browsed it

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!