Home  >  Article  >  Backend Development  >  PHP anonymous function and use clause usage examples_php tips

PHP anonymous function and use clause usage examples_php tips

WBOY
WBOYOriginal
2016-05-16 19:56:541304browse

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 on this site: "Summary of PHP operating office document skills (including word, excel, access, ppt)", "php date Time usage summary", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation Introductory tutorial " and " Summary of common PHP database operation skills "

I hope this article will be helpful to everyone in PHP programming.

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