Home > Backend Development > PHP Problem > How to write anonymous function in php

How to write anonymous function in php

silencement
Release: 2023-02-24 22:52:02
Original
3053 people have browsed it

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

Examples

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

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template