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的session cookie错误

只要你写过PHP代码,相信都遇上过这个大多时候都令人莫明其妙的warning吧..今天我们就来搞定它...............   看了PHP手册,回答如下:   消息“Warnin...

PHP简单获取网站百度搜索和搜狗搜索收录量的方法

PHP简单获取网站百度搜索和搜狗搜索收录量的方法

本文实例讲述了PHP简单获取网站百度搜索和搜狗搜索收录量的方法。分享给大家供大家参考,具体如下: 获取网站百度搜索和搜狗搜索的收录量代码,可以用于获取网站域名在搜索引擎的收录数量,一直想...

PHP数组对比函数,存在交集则返回真,否则返回假

复制代码 代码如下: <?php $array1 = array('a', 'b', 'c', 'd'); $array2 = array('a', 'c'); $array3 =...

php使用Imagick生成图片的方法

本文实例讲述了php使用Imagick生成图片的方法。分享给大家供大家参考。具体如下: 这里使用Imagick 生成图片 解决了图片写中文文字乱码问题,添加支持的字体 public...

CentOS安装php v8js教程

CentOS release 5.11 (Final),CentOS release 6.6 (Final) x64测试通过。 gcc版本,glibc版本,libstdc++.so.6版...