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

PHP anonymous function and use clause usage examples_php tips

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 19:56:54
Original
1357 people have browsed it

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');

Copy after login

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 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');

Copy after login

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.

Related labels:
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template