zoukankan      html  css  js  c++  java
  • php闭包简单实例

    <?php  
    function getClosure($i)  
    {  
            $i = $i.'-'.date('H:i:s');  
            return function ($param) use ($i) {  
                    echo "--- param: $param ---
    ";  
                    echo "--- i: $i ---
    ";  
            };  
    }  
      
    $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
    

    个人觉得闭包使用的意义不大,用来看别人的源码就好

  • 相关阅读:
    美团面试(c++方向)
    浪潮面试-软开
    ofo C++面试
    B树、B+树等
    爱奇艺2017秋招笔试(C++智能设备方向)
    腾讯内推一面C++
    i++ 相比 ++i 哪个更高效?为什么?
    进程间的通讯(IPC)方式
    一台服务器能够支持多少TCP并发连接呢?
    可重入和不可重入
  • 原文地址:https://www.cnblogs.com/cxscode/p/7520110.html
Copyright © 2011-2022 走看看