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程序设计有所帮助。

相关文章

sae使用smarty模板的方法

Smarty是非常流行的模板系统,它分离了业务和逻辑、执行速度快,在php网站中有广泛的运用。 不过在部署到sina app engine(sae)上时出现了问题,因为sae作为云计算平...

PHP6新特性分析

本文讲述了PHP6的新特性。分享给大家供大家参考,具体如下: 1.支持Unicode 支持Unicode是有其必然,虽然Unicode占用较多的空间,但Unicode带来的便利性,远超...

PHP简单实现断点续传下载的方法

本文实例讲述了PHP实现断点续传下载的方法。分享给大家供大家参考。具体如下: $fname = 'http://XXXX/MMLDZG.mp3'; $fp = fopen($fnam...

一致性哈希算法以及其PHP实现详细解析

一致性哈希算法以及其PHP实现详细解析

在做服务器负载均衡时候可供选择的负载均衡的算法有很多,包括:  轮循算法(Round Robin)、哈希算法(HASH)、最少连接算法(Least Connection)、响应...

PHP 采集获取指定网址的内容

参考别人想法变成自己的想法,你会发现慢慢下来以后你就拥有了临时解决很多问题的思路与方法。复制代码 代码如下:<?php /* 功能:获取页面内容,存储下来阅读; lost63 */...