-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosures.php
50 lines (40 loc) · 951 Bytes
/
closures.php
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
<?php
$a->count = 1;
$b->count = 32;
$c->count = 17.5;
$d->count = -9;
$countObjects = array($a, $b, $c, $d);
//define on the fly
usort($countObjects, function($a, $b) {
if ($a->count > $b->count) {
return 1;
} else if ($a->count == $b->count) {
return 0;
}
return -1;
});
// store to a variable
$sortReverse = function($a, $b) {
if ($a->count > $b->count) {
return -1;
} else if ($a->count == $b->count) {
return 0;
}
return 1;
};
print_r($countObjects);
usort($countObjects, $sortReverse);
print_r($countObjects);
// use existing variables in scope
$shouldReverse = true; // can't change this after definition of the closure
$sortDependent = function($a, $b) use ($shouldReverse) {
if ($a->count > $b->count) {
return $shouldReverse ? -1 : 1;
} else if ($a->count == $b->count) {
return 0;
}
return $shouldReverse ? 1 : -1;
};
usort($countObjects, $sortDependent);
print_r($countObjects);
var_dump($sortDependent);