PHP实现事件机制的方法

yipeiwu_com6年前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常用经典函数集锦【数组、字符串、栈、队列、排序等】

本文实例总结了php常用经典函数。分享给大家供大家参考,具体如下: 数组函数 数组操作 range(start,end) 创建一个数组,值从start开始,一直到end结束 如果r...

浅析Dos下运行php.exe,出现没有找到php_mbstring.dll 错误的解决方法

在php.ini文件中将 extension=php_mbstring.dll 移动到 extension=php_exif.dll 之前. 因为 exif 要调用 mbstring,...

php的$_FILES的临时储存文件与回收机制实测过程

php的$_FILES的临时储存文件与回收机制实测过程

我想有跟我一样的想法的人会这样处理的: 上传的文件只是想临时使用,不需要把原文件保存备用,如resize之类的操作,且这些后期的操作会出现在第二轮从客户端请求时才操作的,如先上传,把上传...

PHP清除字符串中所有无用标签的方法

本文实例讲述了PHP清除字符串中所有无用标签的方法。分享给大家供大家参考。具体实现方法如下: 很多时候需要输出一些 “纯” 字符串,也就是去除任何杂质,例如 Html 标签、空格之类的文...

PHPExcel读取EXCEL中的图片并保存到本地的方法

HPExcel是相当强大的 MS Office Excel 文档生成类库,当需要输出比较复杂格式数据的时候,PHPExcel 是个不错的选择。 经过认真研究API文档和查看官方文档,终于...