本文摘自PHP中文网,作者怪我咯,侵删。
Closure,匿名函数,又称为Anonymous functions,是php5.3的时候引入的。匿名函数就是没有定义名字的函数。这点牢牢记住就能理解匿名函数的定义了。PHP Closure类之前在PHP预定义接口中介绍过,但它可不是interface哦,它是一个内部的final类。Closure类是用来表示匿名函数的,所有的匿名函数都是Closure类的实例。
1 2 3 4 5 6 7 8 9 10 | $func = function () {
echo 'func called' ;
};
var_dump( $func );
$reflect = new ReflectionClass( 'Closure' );
var_dump(
$reflect ->isInterface(),
$reflect ->isFinal(),
$reflect ->isInternal()
);
|
Closure类结构如下:
Closure::construct ― 用于禁止实例化的构造函数
Closure::bind ― 复制一个闭包,绑定指定的$this对象和类作用域。
Closure::bindTo ― 复制当前闭包对象,绑定指定的$this对象和类作用域。
看一个绑定$this对象和作用域的例子:
1 2 3 4 5 6 7 8 9 | class Lang
{
private $name = 'php' ;
}
$closure = function () {
return $this ->name;
};
$bind_closure = Closure::bind( $closure , new Lang(), 'Lang' );
echo $bind_closure ();
|
另外,PHP使用魔术方法invoke()可以使类变成闭包:
1 2 3 4 5 | class Invoker {
public function invoke() { return METHOD;}
}
$obj = new Invoker;
echo $obj ();
|
以上就是php Closure类的使用方法的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
php mysqli用法介绍
pdo如何操作大数据对象
总结sql server中常用函数使用方法
php实现标签云的代码
php弹出对话框实现重定向示例代码
mysql索引基础详解
php为什么使用redis
php 屏蔽关键字的方法
mysql触发器在php项目中用来做信息备份、恢复和清空
php中mysqli处理查询结果集的多个方法
更多相关阅读请进入《Closure》频道 >>
机械工业出版社
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。
转载请注明出处:木庄网络博客 » php Closure类的使用方法