Home > php教程 > php手册 > body text

PHP中Closure类的使用方法及详解

PHP中文网
Release: 2016-06-06 19:41:19
Original
895 people have browsed it

PHP中Closure类的使用方法及详解,phpclosure

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
);
Copy after login

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
Copy after login

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

class Invoker {
  public function __invoke() {return __METHOD__;}
}
$obj = new Invoker;
echo $obj(); //Invoker::__invoke
Copy after login

以上内容就是小编给大家分享的PHP中Closure类的使用方法及详解,希望大家喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!