php “事件监听” =_=

PHP 的事件监听机制与javascript的算是差不多一个模子的吧

< ?php
//事件原型
class Event {
	private $handlers = array();
	function addEventListener($e, $handler) {
		empty($this->handlers[$e]) && $this->handlers[$e] = array();
		array_push($this->handlers[$e], $handler);
	}
 
	function callEventHandler($e, $param = null) {
		if(empty($this->handlers[$e])) {
			return false;
		}
 
		if(empty($param) && func_num_args() > 1) {
			$param = array_slice(func_get_args(), 1);
		}
 
		foreach($this->handlers[$e] as $fun) {
			if(is_string($fun) && function_exists($fun)) {
				call_user_func($fun, $this);
			} else
				if(is_array($fun)) {
					list($class, $method) = $fun;
					if(method_exists($class, $method)) {
						call_user_func(array($class, $method), $this);
					}
				} else {
					//call func no exist
				}
		}
	}
}
?>

Read the rest of this entry »