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

How to use php anonymous functions and use clauses

怪我咯
Release: 2023-03-11 17:56:01
Original
1101 people have browsed it

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');
Copy after login

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');
Copy after login

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');
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template