PHP's anonymous function is a new addition after the php5.3, after more and more frameworks to support the high version of PHP, have used this function, the manual explanation is more difficult to understand, then we put aside the manual, in code to cut in, hope that everyone can better understand.
function of a variable
Before we talk about anonymous functions, we need to talk about variable functions
1. First, we define a common function
function test ($a, $b) {return $a + $b; } $test = Test (); Echo $test; res = 3
2. Change it to a variable function
function test ($a, $b) {return $a + $b;} $test = ' test '; echo $test; res = 3
The variable function is to assign a function name to a variable, and then use the $test () or the parameter $test to do so.
Second, anonymous function
1, anonymous function definition
An anonymous function, as the name implies, is a function without a function name.
We remove the function name from the example above as an anonymous function, as follows:
function () {}; This code is the body of the anonymous function without the name of the function, remember that "the end needs to be well divided" $test = function () {return ' 1111111111111 '; }; $test = function ($a, $b) {return $a + $b; }; This code is a standard anonymous function, has the function body, has the return value, here the return value is not return, but returns to the variable $test.
As for why you should add a semicolon at the end, you can understand this:
The assignment of an ordinary variable $name = ' Zhangsan '; Variable assignment is the need to add a semicolon at the end.
This is an anonymous function, which is also the assignment of variables, so the semicolon is understood.
2. Use of anonymous functions
$test = function () {return ' 1111111111111 '; }; Echo $test (); As with variable functions $test = function ($a, $b) {return $a + $b; }; Echo $test (); Similarly, incoming parameters
Iii. questions (meaning of anonymous functions)
See here, we inevitably have doubts, this variable function we use less, this anonymous function depends on the implementation of no ordinary function, then this anonymous function what is the meaning of the existence?
Anonymous functions are not designed to follow the imitation of JS, the main purpose of PHP's anonymous function is to these two functions "closure function", "callback function".
About closures and callbacks we'll talk to you about this next article.
PHP anonymous function (i)