PHP 5.3 加入了闭包语法,也就是匿名函数,允许开发者申明行内函数和在变量中保存.虽然这个语法和JavaScript的闭包相比有点怪异,但是对于PHP语言来说,这是一个良好的补充.
实例代码如下:
- <?php
-
-
-
- function callback($callback) {
- $callback();
- }
-
-
-
-
- callback(function() {
- print "This is a anonymous function.<br />/n";
- });
-
-
-
-
-
-
-
- $msg = "Hello, everyone";
- $callback = function () use ($msg) {
- print "This is a closure use string value, msg is: $msg. <br />/n";
- };
- $msg = "Hello, everybody";
- callback($callback);
-
-
-
-
-
- $msg = "Hello, everyone";
- $callback = function () use (&$msg) {
- print "This is a closure use string value lazy bind, msg is: $msg. <br />/n";
- };
- $msg = "Hello, everybody";
- callback($callback);
-
-
-
-
-
-
-
- $obj = (object) "Hello, everyone";
- $callback = function () use ($obj) {
- print "This is a closure use object, msg is: {$obj->scalar}. <br />/n";
- };
- $obj = (object) "Hello, everybody";
- callback($callback);
-
-
-
-
-
-
- $obj = (object) "Hello, everyone";
- $callback = function () use ($obj) {
- print "This is a closure use object, msg is: {$obj->scalar}. <br />/n";
- };
- $obj->scalar = "Hello, everybody";
- callback($callback);
-
-
-
-
- $obj = (object) "Hello, everyone";
- $callback = function () use (&$obj) {
- print "This is a closure use object lazy bind, msg is: {$obj->scalar}. <br />/n";
- };
- $obj = (object) "Hello, everybody";
- callback($callback);
-
-
-
-
-
-
-
-
-
-
-
-
-
- function counter() {
- $counter = 1;
- return function() use(&$counter) {return $counter ++;};
- }
- $counter1 = counter();
- $counter2 = counter();
- echo "counter1: " . $counter1() . "<br />/n";
- echo "counter1: " . $counter1() . "<br />/n";
- echo "counter1: " . $counter1() . "<br />/n";
- echo "counter1: " . $counter1() . "<br />/n";
- echo "counter2: " . $counter2() . "<br />/n";
- echo "counter2: " . $counter2() . "<br />/n";
- echo "counter2: " . $counter2() . "<br />/n";
- echo "counter2: " . $counter2() . "<br />/n";
- ?>
(责任编辑:admin) |