Intro
PHP 5.3以後Closure / Anonymous Function是一個重大突破,其中callback
、closure
、anonymous function
,與 callable
都是指同一設計模式。
Guide
PHP.net上已有不錯的文獻:
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";
});