Heim  >  Artikel  >  Backend-Entwicklung  >  PHP匿名函数和use子句用法实例_PHP

PHP匿名函数和use子句用法实例_PHP

WBOY
WBOYOriginal
2016-05-28 11:48:171002Durchsuche

本文实例讲述了PHP匿名函数和use子句用法。分享给大家供大家参考,具体如下:

下面方法输出的是hello world

$param1和$param2是闭包变量

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

下面的方式 输出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');

下面的方式 输出hello everybody

$param2中多了一个引用

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

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn