Recently tracked Yii source code involved in the binding event behavior and so on, so that they handwritten a simplest event binding implementation
Class eventhandle {private static $_map = array ();//similar to the jquery binding event public Function on ($name, $callback) {if (!is_callable ($callback)) return false;if (!isset (self::$_map[$ Name]) {self::$_map[$name] = array ();} self::$_map[$name][] = $callback;} Trigger Event 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;} Remove an event-specific callback function 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;}} Event Object class event {public static $options = array ();p Ublic funcTion __construct ($options = array ()) {$this->options = $options;}} Through the function when the callback function Function start1 ($event) {echo ' start1asdaa<br> '; var_dump ($event);} Through the method of the class when the callback function 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 (' name ' => ' hhhh ', ' age ' => 25));
The results appear as follows:
Start1asdaaobject (Event) [2] public ' options ' = + Array (size=2) ' name ' = = String ' hhhh ' (length=4) ' AG E ' = = int 25
PHP Implements event binding