[PHP] Closure / Anonymous Function 匿名函式指南

Intro

PHP 5.3以後Closure / Anonymous Function是一個重大突破,其中callbackclosureanonymous function,與 callable都是指同一設計模式。


Guide

PHP.net上已有不錯的文獻:

PHP Anonymous functions

PHP Closure sample code

PHP Callbacks / Callables

PHP Callables hint sample code

另外點燈坊有一篇蠻完整的文章:如何使用 Closure?


Example

來些Sample Cdoe:

Closure

function myClosure($hi) 
{
    return function($name) use ($hi) {
        return sprintf("%s, %s", $hi, $name);
    };
}

$foo = myClosure("Hello");
echo $foo("World");

// Result:
// Hello World

Anonymous Function

For Callback:

/**
 * @param int $start
 * @param int $end
 * @param callable $callback(int $handlingNumber, int $sum)
 */
function counter($start, $end, callable $callback=null) {

    $count = 0;
    for ($i=$start; $i <= $end; $i++) { 
        $count += $i;
        if ($callback) {
            $callback($i, $count);
        }
    }
    return $count;
}

$count = counter(1, 10, function($number, $count) {
    echo "The handling number is {$number} and the sum is {$count}\n";
});

Leave a Reply

Your email address will not be published. Required fields are marked *