Home > Article > Backend Development > What is php closure function
In PHP, anonymous functions (Anonymous functions), also called closures, allow the temporary creation of a function without a specified name. Often used as a parameter for callback functions. Of course, there are other applications as well.
Note: php closure is only available after PHP5.3 version
What is a closure?
A closure is a block of code that can contain free (not bound to a specific object) variables; these variables are not defined within this code block or in any global context, but in the defining code block defined in the environment (local variables). The word "closure" comes from the combination of a block of code to be executed (because the free variables are contained within the block, these free variables and the objects they refer to are not released) and the binding provided for the free variables. Computing environment (scope). In the field of programming, we can say it in layman's terms: child functions can use local variables in the parent function. This behavior is called closure.
PHP anonymous functions and closures use the same syntax as ordinary functions, but anonymous functions and closures are actually objects disguised as functions.
Anonymous function:
is a function without a name. Anonymous functions can be assigned to variables and objects passed. However, anonymous functions are still functions, so they can be called, and Pass in parameters. Anonymous functions are particularly suitable as callbacks for functions or methods.
Closure:
refers to a function that encapsulates the surrounding state when it is created. Even if a closure The environment no longer exists, but the state encapsulated in the closure still exists.
Note: In theory, closures and anonymous functions are different concepts. However, PHP treats them as the same concept.
The syntax of closures is equivalent Simple, the only keyword you need to pay attention to is use, which connects the closure and external variables.
$a = function() use($b) { //TO-DO };
Here are a few examples of how to implement closures:
//例一:把匿名函数当做参数传递,并且调用它 function callFunc( $func ) { $func( "some string\r\n" ); } $printStrFunc = function( $str ) { echo $str; };
//例二:也可以直接将匿名函数进行传递。如果你了解js,这种写法可能会很熟悉 callFunc( $printStrFunc ); callFunc( function( $str ) { echo $str; } );
Although the syntax and implementation of closures are very simple, they are not easy to use well.
Benefits of closure:
1. Reduce foreach loop code
2. Reduce function parameters
3. Unlocking recursive functions
Recommended tutorial:PHP video tutorial
The above is the detailed content of What is php closure function. For more information, please follow other related articles on the PHP Chinese website!