PHP闭包定义与使用简单示例
作者:程序生(Codey) 时间:2023-11-23 03:12:15
本文实例讲述了PHP闭包定义与使用。分享给大家供大家参考,具体如下:
<?php
function getClosure($i)
{
$i = $i.'-'.date('H:i:s');
return function ($param) use ($i) {
echo "--- param: $param ---\n";
echo "--- i: $i ---\n";
};
}
$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
希望本文所述对大家PHP程序设计有所帮助。
来源:http://www.cnblogs.com/cxscode/p/7520110.html
标签:PHP,闭包
0
投稿
猜你喜欢
python在Windows下安装setuptools(easy_install工具)步骤详解
2022-10-18 19:40:23
图像检索之基于vlfeat实现SIFT特征
2021-11-18 13:13:40
如何让用户再次访问我的网站时不需再提交相关信息?
2010-05-16 15:05:00
python实现高斯投影正反算方式
2022-11-17 08:58:19
python flask实现分页的示例代码
2021-04-01 09:55:23
Python爬虫框架Scrapy实战之批量抓取招聘信息
2022-03-28 11:38:09
windows下安装make及使用makefile文件
2023-05-08 07:50:53
Python用selenium实现自动登录和下单的项目实战
2021-02-04 18:29:44
Python实现简单求解给定整数的质因数算法示例
2021-05-27 09:23:08
MYSQL建立外键失败几种情况记录Can't create table不能创建表
2024-01-22 19:57:22
python的pdb调试命令的命令整理及实例
2022-10-01 01:47:12
css学习笔记:表格隔行点击变色
2009-04-30 13:15:00
mysql执行时间为负数的原因分析
2024-01-19 12:21:20
使用pickle存储数据dump 和 load实例讲解
2023-05-19 18:50:18
python实现比较两段文本不同之处的方法
2021-01-29 17:53:43
安装sql server 2008 management提示已安装 SQL Server 2005 Express的解决方法
2024-01-15 12:49:03
举例详解JavaScript中Promise的使用
2024-06-05 09:58:07
Golang 使用gorm添加数据库排他锁,for update
2024-01-29 09:34:53
php中Array2xml类实现数组转化成XML实例
2023-07-14 21:48:13
python process模块的使用简介
2023-08-05 13:13:13