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

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

jacklove
jackloveasal
2018-06-27 17:49:141494semak imbas

这篇文章主要介绍了PHP闭包定义与使用,结合简单实例形式分析了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实例

PHP代码重构方法漫谈_php技巧

PHP实现负载均衡下的session共用功能php技巧


Atas ialah kandungan terperinci PHP闭包定义与使用简单示例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