Home > Article > Backend Development > What is an anonymous function in PHP? How is it different from ordinary functions? (detailed explanation and examples)
The previous article introduced you to "What is a recursive function in PHP? What are the basic elements? What is its purpose? (Attached code) 》, this article continues to introduce to you what is a recursive function in PHP? What are the basic elements? What is its purpose? (Code attached) This article will give you different gains. Let’s continue to explore the mysteries of PHP together! ! !
#What is an anonymous function?
If you declare a function and the function does not have a function name, then the function is an anonymous function
Usage:
Use variables to receive anonymous functions
Variable name=
function (){
Function body:
};
(Note that there must be points here No. ends, because anonymous functions belong to expressions)
We use code as an example: (ordinary function)
<?php function demo(){ echo '我不想上班'; } demo (); ?>
Code explanation:
First define a Ordinary function function demo(); then outputs (echo) a string of strings, and then we call the function by adding () to the function name. Running this code will get the content we want to output. The code demonstration results are as follows:
Similarly, we first define a function function that outputs (echo) a string; then when we run it, we find that an error will be reported, and the end of the file is not found. We defined An anonymous function cannot be called because it has no name, so it does not belong to a function, it belongs to a type, but if we add a semicolon at the end, the running result will find that it will not report an error, but although our running result does not report an error, But we can't call it, thinking that the function is not named, so we need to assign it to a variable. After we assign the value, we can call it through the variable function;
(code of anonymous function Demo)
<?php function demo(){ echo '我不想上班'; } demo (); $test = function(){ echo '只想在家呆着' ; }; //变量函数 $test(); ?>
The code demonstration results are as follows:
The above case is an anonymous function.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What is an anonymous function in PHP? How is it different from ordinary functions? (detailed explanation and examples). For more information, please follow other related articles on the PHP Chinese website!