Home  >  Article  >  Backend Development  >  How to use php anonymous functions and use clauses

How to use php anonymous functions and use clauses

怪我咯
怪我咯Original
2017-06-28 11:46:171068browse

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!

Statement:
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