One: anonymous function (can be used in php5.3.0 or above)
The anonymous function (Anonymous functions) in PHP, also called the closure function (closures), allows you to specify a function without a name. The most common is the parameter values of the callback function. (http://php.net/manual/zh/functions.anonymous.php)
The definition of an anonymous function:
$closureFunc = function () {
....
};
Eg: assign an anonymous function to a variable and call it through a variable
Copy Code
Closurefunc=function (Closurefunc = function (str) {
Echo $str;
};
$closureFunc ("Hello world!");
Copy Code
Output: Hello world!
Two: Closures
2.1 Put the anonymous function in the normal function, you can also return the anonymous function, which constitutes a simple closure
Copy Code
function ClosureFunc1 () {
Func=function () echo "Hello";; Func = function () {echo "Hello";}; Func ();
}
ClosureFunc1 ();
Output: Hello
Copy Code
2.2 Referencing local variables in anonymous functions
Copy Code
function ClosureFunc2 () {
Num=1; num = 1; Func = function () {
echo num;
};num; }; Func ();
}
CLOSUREFUNC2 ();
notice:undefined Variable:num
Copy Code
The above function, after running, will report notice error, that we can not use the local variables in the anonymous function, this time we will refer to a PHP keyword using the code as follows
Copy Code
function ClosureFunc2 () {
Num=1; num = 1; Func = function () use (num) echo$num;; num) {echo $num;}; Func ();
}
CLOSUREFUNC2 ();
Output: 1
Copy Code
2.3 Returning anonymous functions
Copy Code
function closureFunc3 () {
Num=1; num = 1; Func = function () use (num) echo$num;; Return num) {echo $num;}; return func;
}
FUNC=CLOSUREFUNC3 ();//function returns an anonymous function func = closureFunc3 (); function returns an anonymous function func (); And then we're using $func () to call
Output: 1
Copy Code
2.4 How do we give anonymous functions a reference when we return an anonymous function? In fact, the same as the normal function pass parameters
Copy Code
function ClosureFunc4 () {
Num=1; num = 1; func = function (str) use (str) use (num) {
echo Num;echo "\ n"; Echo num; echo "\ n"; Echo str;
};
return func;
}func; } func = ClosureFunc4 ();
$func ("Hello, Closure4");
Output:
1
Hello, Closure4.
Copy Code
2.5 How to use closures to change the value of the variables referenced by the context.
Copy Code
function ClosureFunc5 () {
Num=1; num = 1; Func = function () use (num) echo "\ n";