PHP Implements event binding

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.