Home >Backend Development >PHP Problem >what is php closure
php closure is to temporarily create a function without a name, which is often used as a callback function. In layman's terms: child functions can use local variables in the parent function. This behavior is called closure.
When mentioning closures, you have to think of anonymous functions, also called closure functions (closures). It seems that PHP closure implementation mainly relies on it. . Declare an anonymous function like this:
The code is as follows:(Recommended learning: PHP video tutorial)
$func = function() { }; //带结束符
As you can see, the anonymous function is because Without a name, you need to return it to a variable if you want to use it. Anonymous functions can also declare parameters like ordinary functions, and the calling method is also the same:
The code is as follows:
$func = function( $param ) { echo $param; }; $func( 'some string' ); //输出: //some string
Implement closure
Pass anonymous functions as parameters in ordinary functions, and they can also be returned. This implements a simple closure.
//在函数里定义一个匿名函数,并且调用它 function printStr() { $func = function( $str ) { echo $str; }; $func( 'some string' ); } printStr(); 输出: some string
The above is the detailed content of what is php closure. For more information, please follow other related articles on the PHP Chinese website!