Home >Backend Development >PHP Tutorial >Usage of use clause in PHP anonymous function

Usage of use clause in PHP anonymous function

墨辰丷
墨辰丷Original
2018-06-04 17:14:271808browse

This article mainly introduces the usage of the use clause in PHP anonymous functions. Interested friends can refer to it. I hope it will be helpful to everyone.

The sample code is as follows:

function test()
{
  $param2 = 'every';
  // 返回一个匿名函数
  return function ($param1) use ($param2) {
    // use子句 让匿名函数使用其作用域的变量
    $param2 .= 'one';
    print $param1 . ' ' . $param2;
  };
}
$anonymous_func = test();
$anonymous_func('hello');

Output result: hello world

$param1 and $param2 are closure variables

function test()
{
  $param2 = 'everyone';
  $func = function ($param1) use ($param2) {
    // use子句 让匿名函数使用其父作用域的变量
    print $param1 . ' ' . $param2;
  };
  $param2 = 'everybody';
  return $func;
}
$anonymous_func = test();
$anonymous_func('hello');

Output result: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');

Output result:hello everybody

There is an additional quote in

$param2

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Example analysis of PHP mathematical operations and data processing methods

PHP calculates the sum and product of values ​​in an array Method and example analysis

Detailed analysis of the difference between PHP global variables and super global variables

The above is the detailed content of Usage of use clause in PHP anonymous function. 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