PHP实现事件机制的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了PHP实现事件机制的方法。分享给大家供大家参考。具体如下:

<?php
/**
* 事件
*/
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);
  }
 }
}

希望本文所述对大家的php程序设计有所帮助。

相关文章

php自定义函数实现统计中文字符串长度的方法小结

本文实例讲述了php自定义函数实现统计中文字符串长度的方法。分享给大家供大家参考,具体如下: 中文字符计算为2个字符 英文字符计算为1个 代码 /** * 可以统计中文字符串长度的...

php使用curl抓取qq空间的访客信息示例

config.php 复制代码 代码如下:<?phpdefine('APP_DIR', dirname(__FILE__));define('COOKIE_FILE', APP_D...

CentOS 6.2使用yum安装LAMP以及phpMyadmin详解

介绍如何在CentOs6.2下面使用YUM配置安装LAMP环境,一些兄弟也很喜欢使用编译的安装方法,个人觉得如果不是对服务器做定制,用yum安装稳定简单,何必去download&make...

PHP+JS三级菜单联动菜单实现方法

本文实例讲述了PHP+JS三级菜单联动菜单实现方法。分享给大家供大家参考,具体如下: <html> <head> <title>...

php提交post数组参数实例分析

本文实例分析了php提交post数组参数的用法。分享给大家供大家参考,具体如下: 首先php中要想从页面传送数组到服务端a,要在页面上多个空间同名,而且对于名称有要求,那就是 name=...