PHP anonymous functions and closures use the same syntax as ordinary functions, but anonymous functions and closures are actually objects disguised as functions.
Anonymous functions: It is a function without a name. Anonymous functions can be assigned to variables and passed as objects. However, anonymous functions are still functions, so they can be called and parameters can be passed in. 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 the environment in which the closure is located no longer exists, the state encapsulated in the closure still exists.
Note: Theoretically Speaking of which, closures and anonymous functions are different concepts. However, PHP treats them as the same concept.
How to write anonymous functions
$func = function(){ };//带结束符
$func = function ($param) { echo($param); }; $func('hello world');
function closureFunc1 () { $func = function () { echo "hello"; }; $func(); } closureFunc1(); //输出: hello
The above is the detailed content of How to write anonymous function in php. For more information, please follow other related articles on the PHP Chinese website!