最近跟踪yii源码 里面涉及到了绑定事件行为之类,于是自己手写了一个最简单的事件绑定实现
复制代码
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
66class EventHandle { private static $_map = array(); //类似jquery绑定事件 public function on($name, $callback) { if(!is_callable($callback)) return false; if(!isset(self::$_map[$name])) { self::$_map[$name] = array(); } self::$_map[$name][] = $callback; } //触发事件 public function trigger($name, $event) { if(!isset(self::$_map[$name])) return false; $function_arr = self::$_map[$name]; foreach($function_arr as $function) { call_user_func($function, $event); } return true; } //移除某个事件特定的回调函数 public function remove($name, $callback) { if(!isset(self::$_map[$name])) return false; $map = self::$_map[$name]; $pos = array_search($callback, $map, true); if($pos >= 0) { array_splice($map, $pos, 1); self::$_map[$name] = $map; } return true; } } //事件对象 class Event { public static $options = array(); public function __construct($options = array()) { $this->options = $options; } } //通过函数当回调函数 function start1($event) { echo 'start1asdaa<br>'; var_dump($event); } //通过类的方法当回调函数 class EventCallback { public function start3($event) { echo 'start3<br>'; } } $eventhandle = new EventHandle(); $eventhandle->on('start', "start1"); $eventhandle->on('start', array("EventCallback", "start3")); $eventhandle->remove('start', array("EventCallback", "start3")); $eventhandle->trigger('start', new Event(array('name' => 'hhhh', 'age' => 25)));
出现的结果如下:
复制代码
1
2
3
4
5start1asdaa object(Event)[2] public 'options' => array (size=2) 'name' => string 'hhhh' (length=4) 'age' => int 25
转载于:https://blog.51cto.com/chinalx1/2140806
最后
以上就是追寻蛋挞最近收集整理的关于php实现事件绑定的全部内容,更多相关php实现事件绑定内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复