• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    PHP闭包定义与使用简单示例

    本文实例讲述了PHP闭包定义与使用。分享给大家供大家参考,具体如下:

    ?php
    function getClosure($i)
    {
      $i = $i.'-'.date('H:i:s');
      return function ($param) use ($i) {
        echo "--- param: $param ---\n";
        echo "--- i: $i ---\n";
      };
    }
    $c = getClosure(123);
    $i = 456;
    $c('test');
    sleep(3);
    $c2 = getClosure(123);
    $c2('test');
    $c('test');
    /*
    output:
    --- param: test ---
    --- i: 123-21:36:52 ---
    --- param: test ---
    --- i: 123-21:36:55 ---
    --- param: test ---
    --- i: 123-21:36:52 ---
    */
    
    

    再来一个实例

    $message = 'hello';
    $example = function() use ($message){
     var_dump($message);
    };
    echo $example();
    //输出hello
    $message = 'world';
    //输出hello 因为继承变量的值的时候是函数定义的时候而不是 函数被调用的时候
    echo $example();
    //重置为hello
    $message = 'hello';
    //此处传引用
    $example = function() use($message){
     var_dump($message);
    };
    echo $example();
    //输出hello
    $message = 'world';
    echo $example();
    //此处输出world
    //闭包函数也用于正常的传值
    $message = 'hello';
    $example = function ($data) use ($message){
     return "{$data},{$message}";
    };
    echo $example('world');
    //此处输出world,hello
    
    

    更多关于PHP相关内容感兴趣的读者可查看本站专题:《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《PHP数学运算技巧总结》及《PHP运算与运算符用法总结》、

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

    您可能感兴趣的文章:
    • PHP闭包(Closure)使用详解
    • PHP闭包函数详解
    • php的闭包(Closure)匿名函数详解
    • PHP闭包函数传参及使用外部变量的方法
    • 浅谈PHP 闭包特性在实际应用中的问题
    • PHP中的闭包(匿名函数)浅析
    • PHP闭包实例解析
    • php的闭包(Closure)匿名函数初探
    • PHP 闭包详解及实例代码
    • php基于闭包实现函数的自调用(递归)实例分析
    • PHP 闭包获取外部变量和global关键字声明变量的区别讲解
    • 浅析PHP中的闭包和匿名函数
    • PHP基于闭包思想实现的BT(torrent)文件解析工具实例详解
    上一篇:PHP简单实现正则匹配省市区的方法
    下一篇:php微信公众号开发之现金红包
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

    PHP闭包定义与使用简单示例 PHP,闭包,定义,与,使用,简单,