-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathch10p1Closures.php
More file actions
110 lines (105 loc) · 2.44 KB
/
ch10p1Closures.php
File metadata and controls
110 lines (105 loc) · 2.44 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
include_once('generalIncludes.php');
echo '<input id="chapter" type="hidden" value="10">';
echo '<h2>Chapter 10 Closures and Callbacks - Paragraph Closures</h2>';
echo '<h3>Listing 10.1: Creating a closure</h3>';
showcode(<<<'CODE'
function createGreeter($who) {
return function() use ($who) {
echo "Hello $who";
};
}
$greeter = createGreeter("World");
$greeter(); // Hello World
CODE
);
echo '<h3>Listing 10.2: Creating a closure with a reference</h3>';
showcode(<<<'CODE'
// Make sure to use reference here also
function createGreeter2(&$who) {
return function() use (&$who) {
echo "Hello $who \n";
$who = null;
};
}
$who = "world";
$greeter = createGreeter2($who); // Passed in by-reference
$who = ucfirst($who); // changes to World,
// including the closure reference
$greeter(); // Hello World, changes $who to null
var_dump($who); // null
CODE
);
echo '<h3>Listing 10.3: Using $this in closures</h3>';
showcode(<<<'CODE'
class foo
{
public function getClosure() {
return function() { return $this; };
}
}
class bar
{
public function __construct() {
$foo = new foo();
$func = $foo->getClosure();
$obj = $func(); // PHP 5.3: $obj == null
// PHP 5.4: $obj == foo, not bar
}
}
CODE
);
echo '<h3>Listing 10.4, 10.5 and 10.6: Changing $this dynamically and binding</h3>';
showcode(<<<'CODE'
class Greeter
{
public function getClosure() {
return function() {
echo $this->hello;
$this->world();
};
}
}
class WorldGreeter
{
public $hello = "Hello ";
private function world() { echo "World"; }
}
$greeter = new Greeter();
$closure = $greeter->getClosure();
$worldGreeter = new WorldGreeter();
// Rebind $this to $worldGreeter
$newClosure = $closure->bindTo($worldGreeter,'WorldGreeter');
$newClosure();
CODE
);
echo '<h3>Listing 10.7: Using static bind()</h3>';
showcode(<<<'CODE'
class Greeter2
{
public function getClosure() {
return function() {
echo $this->hello;
$this->world();
};
}
}
class WorldGreeter2
{
public $hello = "Hello ";
private function world() { echo "World"; }
}
$greeter = new Greeter2();
$closure = $greeter->getClosure();
$worldGreeter = new WorldGreeter2();
// Rebind $this and scope to $worldGreeter
$newClosure = Closure::bind(
$closure, $worldGreeter, 'WorldGreeter2'
);
$newClosure(); // Hello World
CODE
);
echo '<h3></h3>';
showcode(<<<'CODE'
CODE
);