明辉手游网中心:是一个免费提供流行视频软件教程、在线学习分享的学习平台!

php Closure类的使用方法

[摘要]Closure,匿名函数,又称为Anonymous functions,是php5.3的时候引入的。匿名函数就是没有定义名字的函数。这点牢牢记住就能理解匿名函数的定义了。PHP Closure类之前...
Closure,匿名函数,又称为Anonymous functions,是php5.3的时候引入的。匿名函数就是没有定义名字的函数。这点牢牢记住就能理解匿名函数的定义了。

PHP Closure类之前在PHP预定义接口中介绍过,但它可不是interface哦,它是一个内部的final类。Closure类是用来表示匿名函数的,所有的匿名函数都是Closure类的实例。

$func = function() {
  echo 'func called';
};
var_dump($func); //class Closure#1 (0) { }
$reflect =new ReflectionClass('Closure');
var_dump(
  $reflect->isInterface(), //false
  $reflect->isFinal(), //true
  $reflect->isInternal() //true
);

Closure类结构如下:

Closure::construct — 用于禁止实例化的构造函数
Closure::bind — 复制一个闭包,绑定指定的$this对象和类作用域。
Closure::bindTo — 复制当前闭包对象,绑定指定的$this对象和类作用域。

看一个绑定$this对象和作用域的例子:

class Lang
{
  private $name = 'php';
}
$closure = function () {
  return $this->name;
};
$bind_closure = Closure::bind($closure, new Lang(), 'Lang');
echo $bind_closure(); //php

另外,PHP使用魔术方法invoke()可以使类变成闭包:

class Invoker {
  public function invoke() {return METHOD;}
}
$obj = new Invoker;
echo $obj(); //Invoker::invoke

以上就是php Closure类的使用方法的详细内容,更多请关注php中文网其它相关文章!


学习教程快速掌握从入门到精通的SQL知识。