Home >Backend Development >PHP Tutorial >PHP anonymous function and use clause usage examples, anonymous use clause examples_PHP tutorial
The examples in this article describe the usage of PHP anonymous functions and use clauses. Share it with everyone for your reference, the details are as follows:
The following method outputs hello world
$param1 and $param2 are closure variables
function test() { $param2 = 'every'; // 返回一个匿名函数 return function ($param1) use ($param2) { // use子句 让匿名函数使用其作用域的变量 $param2 .= 'one'; print $param1 . ' ' . $param2; }; } $anonymous_func = test(); $anonymous_func('hello');
The following method outputs hello everyone
function test() { $param2 = 'everyone'; $func = function ($param1) use ($param2) { // use子句 让匿名函数使用其父作用域的变量 print $param1 . ' ' . $param2; }; $param2 = 'everybody'; return $func; } $anonymous_func = test(); $anonymous_func('hello');
The following method outputs hello everybody
There is one more reference in $param2
function test() { $param2 = 'everyone'; $func = function ($param1) use (&$param2) { // use子句 让匿名函数使用其父作用域的变量 print $param1 . ' ' . $param2; }; $param2 = 'everybody'; return $func; } $anonymous_func = test(); $anonymous_func('hello');
Readers who are interested in more PHP-related content can check out the special topics of this site: "Summary of PHP office document operation skills (including word, excel, access, ppt)", "Summary of PHP date and time usage", "php-oriented "Introduction Tutorial on Object Programming", "Summary of PHP String Usage", "Introduction Tutorial on PHP MySQL Database Operation" and "Summary of Common PHP Database Operation Skills"
I hope this article will be helpful to everyone in PHP programming.