Rumah  >  Artikel  >  pembangunan bahagian belakang  >  PHP闭包定义与使用简单示例

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

不言
不言asal
2018-04-13 11:56:201493semak imbas

这篇文章主要介绍了PHP闭包定义与使用,有着一定的参考价值,现在分享给大家,有需要的朋友也可以参考一下

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


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


再来一个实例


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

相关推荐:

 php闭包特性在实际中的应用说明

php闭包函数代码实例详解

Atas ialah kandungan terperinci PHP闭包定义与使用简单示例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn