这篇文章主要介绍了php闭包定义与使用,有着一定的参考价值,现在分享给大家,有需要的朋友也可以参考一下
本文实例讲述了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相关推荐:
一个功能完善、展示信息丰富的电子商店销售平台;针对企业与个人的网上销售系统;开放式远程商店管理;完善的订单管理、销售统计、结算系统;强力搜索引擎支持;提供网上多种在线支付方式解决方案;强大的技术应用能力和网络安全系统,同时拥有灵活多变的商品管理、新闻管理等功能,功能强劲的后台管理界面,它为您提供了多款专业美观的店面样式、俱备完整的购物网站功能、结构简单、容易使用、并设有促销广告和店标自定义功能,操
0
立即学习“PHP免费学习笔记(深入)”;
以上就是PHP闭包定义与使用简单示例的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号