Home  >  Article  >  Backend Development  >  PHP闭包实例解析_php技巧

PHP闭包实例解析_php技巧

WBOY
WBOYOriginal
2016-05-16 20:36:281132browse

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

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

具体形式如下:

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

具体用法实例如下:

<&#63;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)
&#63;>

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

Statement:
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