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";

            }

        }; 

    }

}

参考:

  1. https://wiki.php.net/rfc/closures
  2. http://www.ibm.com/developerworks/cn/opensource/os-php-5.3new2/ 

相关文章

粤ICP备11097351号-1