PHP闭包实例解析

6年以前  |  阅读数:520 次  |  编程语言:PHP 

本文实例分析了PHP程序设计中闭包的概念机用法,分享给大家供大家参考。具体分析如下:

通常来说,闭包也就是PHP的匿名函数, 但是和函数不同的是,闭包可以通过use使用函数声明时所在作用域的变量的值。

具体形式如下:


    $a = function($arg1, $arg2) use ($variable) { 
    // 声明函数闭包到变量$a, 参数为$arg1, $arg2 ,该闭包需使用$variable变量
    }

具体用法实例如下:


    <?php
    $result = 0;

    $one = function()
    { var_dump($result); };

    $two = function() use ($result)
    { var_dump($result); }; // 可以认为 $two这个变量 本身记录了该函数的声明以及use使用的变量的值

    $three = function() use (&$result)
    { var_dump($result); };

    $result++;

    $one();  // outputs NULL: $result is not in scope
    $two();  // outputs int(0): $result was copied
    $three();  // outputs int(1)
    ?>

希望本文所述对大家PHP程序设计的学习有一定的借鉴与帮助作用。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8