class 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)));
出现的结果如下:
start1asdaaobject(Event)[2] public 'options' => array (size=2) 'name' => string 'hhhh' (length=4) 'age' => int 25
php实现事件绑定
原文地址:http://blog.51cto.com/chinalx1/2140806