-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadlocal.php
More file actions
68 lines (57 loc) · 1.68 KB
/
threadlocal.php
File metadata and controls
68 lines (57 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
<?php
class ThreadLocal {
private static $context = null;
private $vars = [];
private $save_callbacks = [];
private $restore_callbacks = [];
public function __construct() {
if ($old = self::$context) {
$old->save();
}
self::$context = $this;
}
public static function getContext() {
if (!self::$context) {
self::$context = new ThreadLocal();
}
return self::$context;
}
public static function assign(&$ref, $value) {
$ref = $value;
self::getContext()->vars[] = [&$ref, $value];
}
public static function onSaveRestore($save, $restore) {
$context = self::getContext();
$context->save_callbacks[] = $save;
$context->restore_callbacks[] = $restore;
}
public static function onSave($callback) {
self::getContext()->save_callbacks[] = $callback;
}
public static function onRestore($callback) {
self::getContext()->restore_callbacks[] = $callback;
}
private function save() {
foreach ($this->vars as $var) {
$var[1] = $var[0];
$var[0] = null;
}
foreach ($this->save_callbacks as $callback) {
call_user_func($callback);
}
}
public function restore() {
if (self::$context === $this) {
return;
}
$old = self::getContext();
$old->save();
foreach ($this->vars as $var) {
$var[0] = $var[1];
}
foreach ($this->restore_callbacks as $callback) {
call_user_func($callback);
}
self::$context = $this;
}
}