龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

php 用PHP实现的事件机制

时间:2014-06-13 02:27来源:网络整理 作者:网络 点击:
分享到:
用PHP实现的事件机制 [代码片段(53行)]
<?php
/**
* 事件
*
* @author xiezhenye <xiezhenye@gmail.com>
* @since 2007-7-20
*/
class Event {
   private $callbacks = array();
   private $holder;

   function __construct() {
       $bt = debug_backtrace();
       if (count($bt) < 2) {
           $this->holder = null;
           return;
       }
       $this->holder = &$bt[1]['object'];
   }

   function attach() {
       $args = func_get_args();
       switch (count($args)) {
           case 1:
               if (is_callable($args[0])) {
                   $this->callbacks[]= $args[0];
                   return;
               }
               break;
           case 2:
               if (is_object($args[0]) && is_string($args[1])) {
                   $this->callbacks[]= array(&$args[0], $args[1]);
               }
               return;
           default:
               return;
       }
   }

   function notify() {
       $bt = debug_backtrace();
       if ($this->holder && 
                ((count($bt) >= 2 && $bt[count($bt) - 1]['object'] !== $this->holder)
                || (count($bt) < 2))) {
           throw(new Exception('Notify can only be called in holder'));   
       }
       foreach ($this->callbacks as $callback) {
           $args = func_get_args();
           call_user_func_array($callback, $args);
       }
   }
}
收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
评论内容为空!
还没有评论,快来抢沙发吧!

热评话题

按钮 内容不能为空!
立刻说两句吧! 查看0条评论
精彩图集

赞助商链接