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

2025-05-29 0 37

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

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

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); //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对象和作用域的例子:

?

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

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

?

1

2

3

4

5
class Invoker {

public function __invoke() {return __METHOD__;}

}

$obj = new Invoker;

echo $obj(); //Invoker::__invoke

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP中Closure类的使用方法及详解 https://www.kuaiidc.com/99989.html

相关文章

发表评论
暂无评论