前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >php关于闭包(匿名函数)的理解

php关于闭包(匿名函数)的理解

作者头像
黄啊码
发布2020-05-29 11:16:02
1.2K0
发布2020-05-29 11:16:02
举报

匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。

匿名函数目前是通过 Closure 类来实现的。

Example #1 匿名函数示例

<?php echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // 输出 helloWorld ?>

闭包函数也可以作为变量的值来使用。PHP 会自动把此种表达式转换成内置类 Closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号:

Example #2 匿名函数变量赋值示例

<?php name); }; greet('World');greet('PHP'); ?>

闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。 PHP 7.1 起,不能传入此类变量: superglobals、 $this 或者和参数重名。【use使用的是参数的副本而已,如果想要真实值,必须使用&】

Example #3 从父作用域继承变量

example(); // 继承 messageexample = function () use (message = 'hello'; // Inherit by-reference example = function () use (&example(); // Closures can also accept regular arguments example = function (arg) use (message) { var_dump(arg . ' ' . message); };

以上例程的输出类似于:

代码语言:javascript
复制
Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"

这些变量都必须在函数或类的头部声明。 从父作用域中继承变量与使用全局变量是不同的。全局变量存在于一个全局的范围,无论当前在执行的是哪个函数。而 闭包的父作用域是定义该闭包的函数(不一定是调用它的函数)。示例如下:

Example #4 Closures 和作用域

products = array(); public function add(product, quantity) { this->products[product) { return isset(this->products[this->products[callback = function (quantity, product) use (tax, &product)); total += (pricePerItem * quantity) * (tax + 1.0); }; array_walk(this->products, my_cart = new Cart; // 往购物车里添加条目 my_cart->add('butter', 1);

Example #5 Automatic binding of $this

this); }; } } object = new Test;function = object->testing();

以上例程会输出:

代码语言:javascript
复制
object(Test)#1 (0) {
}

以上例程在PHP 5.3中的输出:

代码语言:javascript
复制
Notice: Undefined variable: this in script.php on line 8
NULL 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-04-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档