Look at the code below
function test() { $param2 = 'every'; // 返回一个匿名函数 return function ($param1) use ($param2) { // use子句 让匿名函数使用其作用域的变量 $param2 .= 'one'; print $param1 . ' ' . $param2; }; } $anonymous_func = test(); $anonymous_func('hello');
The output is hello world
$param1 and $param2 are closure variables
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 in $param2Quote
function test() { $param2 = 'everyone'; $func = function ($param1) use (&$param2) { // use子句 让匿名函数使用其父作用域的变量 print $param1 . ' ' . $param2; }; $param2 = 'everybody'; return $func; } $anonymous_func = test(); $anonymous_func('hello');
The above is the detailed content of How to use php anonymous functions and use clauses. For more information, please follow other related articles on the PHP Chinese website!