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常见数组排序方法。 一、数组操作的基本函数 数组的键名和值 array_values($arr); 获得数组的值 array_keys($arr); 获得数组的键名...

比较strtr, str_replace和preg_replace三个函数的效率

之前已经分析过strtr的源码了,现在就比较strtr, str_replace和preg_replace的效率:复制代码 代码如下:$str = '111111110000000000...

PHP抽象类和接口用法实例详解

本文实例讲述了PHP抽象类和接口用法。分享给大家供大家参考,具体如下: 前言 对于oop,估计大多数人并不陌生。有些人除PHP外也学习不少其他语言,会发现php的不同之处,可能语法极其丑...

PHP中字符安全过滤函数使用小结

在WEB开发过程中,我们经常要获取来自于世界各地的用户输入的数据。但是,我们“永远都不能相信那些用户输入的数据”。所以在各种的Web开发语言中,都会提供保证用户输入数据安全的函数。在PH...

PHP 日,周,月点击排行统计

复制代码 代码如下: $now=time(); //当前时间 $StrUpdate = "Update $tbl_article set hits=hits+1"; if(date("d...