Home  >  Article  >  Backend Development  >  How to write anonymous function in php

How to write anonymous function in php

silencement
silencementOriginal
2019-09-26 11:03:262889browse

How to write anonymous function in php

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(){ 
    
};//带结束符

Examples

 $func = function ($param) {
     echo($param); 
}; 
 
$func('hello world');

When it comes to anonymous functions, we have to mention closures. Put anonymous functions in ordinary functions, and you can also return anonymous functions, which constitutes a simple closure

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!

Statement:
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
Previous article:Why does php use apache?Next article:Why does php use apache?