PHP 中的Closure
来源:互联网 发布:mac 编译安装php 编辑:程序博客网 时间:2024/06/10 16:36
PHP 中的Closure
Closure,匿名函数,又称为Anonymous functions,是php5.3的时候引入的。匿名函数就是没有定义名字的函数。这点牢牢记住就能理解匿名函数的定义了。
比如下面的代码
function test() { return 100;};function testClosure(Closure $callback){ return $callback();}$a = testClosure(test());print_r($a);exit;
这里的test()永远没有办法用来作为testClosure的参数,因为它并不是“匿名”函数。
所以应该改成这样:
$f = function () { return 100;};function testClosure(Closure $callback){ return $callback();}$a = testClosure($f);print_r($a);exit;
好,如果要调用一个类里面的匿名函数呢?
class C { public static function testC() { return function($i) { return $i+100; }; }}$f = function ($i) { return $i + 100;};function testClosure(Closure $callback){ return $callback(13);}$a = testClosure(C::testC());print_r($a);exit;
应该这么写,其中的C::testC()返回的是一个funciton。
绑定的概念
上面的例子的Closure只是全局的的匿名函数,好了,我现在想指定一个类有一个匿名函数。也可以理解说,这个匿名函数的访问范围不再是全局的了,是一个类的访问范围。
那么我们就需要将“一个匿名函数绑定到一个类中”。
<?phpclass A { public $base = 100;}class B { private $base = 1000;}$f = function () { return $this->base + 3;};$a = Closure::bind($f, new A);print_r($a());echo PHP_EOL;$b = Closure::bind($f, new B , 'B');print_r($b());echo PHP_EOL;
上面的例子中,
绑定之后,就好像A中有这么个函数一样,但是这个函数是public还是private,bind的最后一个参数就说明了这个函数的可调用范围。
对于bindTo,看例子:
<?phpclass A { public $base = 100;}class B { private $base = 1000;}class C { private static $base = 10000;}$f = function () { return $this->base + 3;};$sf = static function() { return self::$base + 3;};$a = Closure::bind($f, new A);print_r($a());echo PHP_EOL;$b = Closure::bind($f, new B , 'B');print_r($b());echo PHP_EOL;$c = $sf->bindTo(null, 'C');print_r($c());
echo PHP_EOL;
原文:http://www.cnblogs.com/yjf512/p/4421289.html
0 0
- PHP 中的Closure
- PHP 中的Closure
- PHP中的Closure闭包
- PHP closure
- php中的匿名函数和闭包(closure)
- php中的匿名函数和闭包(closure)
- php中的匿名函数和闭包(closure)
- PHP closure 匿名函数
- PHP Closure类详解
- PHP Closure类详解
- PHP Closure类详解
- Google Closure Compiler with PHP
- PHP闭包(Closure)
- PHP Closure创建匿名函数
- php中的匿名函数和闭包(closure)及use的作用
- JavaScript中的闭包(Closure)
- Javascript中的闭包(Closure)
- jQuery中的closure设计模式
- 设计模式六大原则
- post_process.glshad
- 性能测试监控总结
- ambari启动hive时报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in
- leetcode-37-sudoku solver
- PHP 中的Closure
- StringUtils
- 时间格式化等操作
- intelliJ IDEA进行spark配置和开发
- C#--设计模式之适配器模式
- 点击事件的坑
- 微信小程序把玩(十八)picker组件
- typer.js,可能是最小但功能也不多的模拟打字效果插件
- MongoDB简介与增删改查