PHP的闭包(closure)
PHP #闭包 #closure2012-11-08 10:05
闭包可以理解是对匿名函数的扩展,它和匿名函数的区别是可以调用函数外部的变量。
比如
$x = 1
$closure = function() use (&$x) { ++$x; }
echo $x . "\n";
$closure();
echo $x . "\n";
$closure();
echo $x . "\n"; 输出:
1 2 3
如果是对象的方法,闭包还可以通过$this获得对像的引用,这使得反射获得闭包函数成为可能。
class Counter
{
private $x;
public function __construct()
{
$this->x = 0;
}
public function increment()
{
$this->x++;
}
public function currentValue()
{
echo $this->x . "\n";
}
}
$class= new ReflectionClass('Counter');
$method = $class->getMethod('currentValue');
$closure = $method->getClosure()
$closure();
$class->increment();
$closure();输出:1
当然闭包也可以应用在函数返回的匿名函数中
class Totalizer {/* http://yige.org/php/ */
static function warnAmount( $amt ) {
$count=0;
return function( $product ) use ( $amt, &$count ) {
$count += $product->price;
print " count: $count\n";
if ( $count > $amt ) {
print " high price reached: {$count}\n";
}
};
}
}参考:
相关文章
- php设置curl的请求头信息 2012/11/08
- PHP与MySQL的存储过程 2012/11/06
- PHP相对路径问题最有效的办法 2012/11/05
- php中header函数参数Cache-control:private的用法 2012/11/01
- PHP的cURL快速入门 2012/10/31
- 修改PHP时区的3种方法 2012/10/31
- PHP加快文件下载 2012/10/31
- PHP用CURL模拟登录新浪微博 2012/10/31
- PHP用FTP实现远程附件上传 2012/10/31
- php多进程实战 2012/10/31