PHP中Closure类的使用方法及详解_php教程-查字典教程网
PHP中Closure类的使用方法及详解
PHP中Closure类的使用方法及详解
发布时间:2016-12-29 来源:查字典编辑
摘要:Closure,匿名函数,又称为Anonymousfunctions,是php5.3的时候引入的。匿名函数就是没有定义名字的函数。这点牢牢记...

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

Closure 类(PHP 5 >= 5.3.0)简介 用于代表 匿名函数 的类. 匿名函数(在 PHP 5.3 中被引入)会产生这个类型的对象,下面我们来看一下PHP Closure类的使用方法及介绍。

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教程学习
    热门php教程学习
    编程开发子分类