-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathch10p2Callbacks.php
More file actions
76 lines (74 loc) · 1.68 KB
/
ch10p2Callbacks.php
File metadata and controls
76 lines (74 loc) · 1.68 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
<?php
include_once('generalIncludes.php');
echo '<input id="chapter" type="hidden" value="10">';
echo '<h2>Chapter 10 Closures and Callbacks - Paragraph Callbacks</h2>';
echo '<h3>Listing 10.8: Using arrays to specify callbacks</h3>';
showcode(<<<'CODE'
Class SomeClass
{
public function method(){}
}
$obj = new SomeClass;
$array = [1,2,3,5,4];
// object method call:
$callback = [$obj, 'method']; // $obj->method() callback
usort($array, $callback);
// or static method:
$callback = ['SomeClass', 'method']; // SomeClass::method()
usort($array, $callback);
CODE
);
echo '<h3>Listing 10.9: Using a class as a callback</h3>';
//@todo sorter needs no (); and usort wants first an array, then the sortes
showcode(<<<'CODE'
class Sorter
{
public function __invoke($a, $b) {
// Sort
return ($a < $b) ? -1 : 1;
}
}
$sorter = new Sorter();
$array = [1,4,2,3,5];
usort($array, $sorter);
print_r($array);
CODE
);
echo '<h3>Listing 10.10: Userland callbacks</h3>';
//@todo Added two ';' and some variables
showcode(<<<'CODE'
function myFunction(){}
Class SomeOtherClass
{
public function method(){}
}
$obj = new SomeOtherClass;
$array = [1,2,3,5,4];// Variable Functions
$callback = "myFunction";
$callback();
// object method call:
$callback = [$obj, 'method']; // $obj->method() callback
$callback();
// or static method:
$callback = ['SomeOtherClass', 'method']; // SomeOtherClass::method()
$callback();
// Closures
$callback = function() { };
$callback();
// Objects with Invoke magic method:
class invokeCallback
{
public function __invoke() { }
}
$callback = new invokeCallback();
$callback();
CODE
);
echo '<h3></h3>';
showcode(<<<'CODE'
CODE
);
echo '<h3></h3>';
showcode(<<<'CODE'
CODE
);