PHP5 的測試筆記 (closure, lambda)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class XRuby {
private $from, $to, $table;

public function __construct($from = "", $to = "", $table = array()) {
$this->from = $from;
$this->to = $to;
$this->table = $table;
}

public function eachRange($func) {
if (is_callable($func)) {

$yield = function() use ($func) {
$args = func_get_args();
call_user_func_array($func, $args);
};

for($i=$this->from; $i<$this->to; $i++) {
$yield($i);
}
}
}

public function eachArray($func) {
if (is_callable($func)) {
foreach($this->table as $k => $v) {
call_user_func_array($func, array($k, $v));
}
}
}
}

$s = function($num) {
echo "<strong>Test Case: ".($num)."</strong><br />";
};

$x = new XRuby(1, 10, array(1 => 'one', 2 => 'two'));

$s(1);
$x->eachRange(function($i) {
echo ($i*$i)."<br />";
});

$s(2);
$x->eachArray(function($k, $v) {
printf("%s => %s<br />", $k, $v);
});

$s(3);
array_walk(
$t = array('1' => 'one', '2' => 'two', '3' => 'three'),
function(&$v, $k) {
printf("%s => %s<br />", $k, $v);
}
);