Home >php教程 >PHP源码 >用PHP实现的事件机制

用PHP实现的事件机制

PHP中文网
PHP中文网Original
2016-05-25 17:14:391082browse

php代码

<?php

/**
* 事件
*
* @author xiezhenye <xiezhenye@gmail.com>
* @since 2007-7-20
*/
class Event {
   private $callbacks = array();
   private $holder;

   function __construct() {
       $bt = debug_backtrace();
       if (count($bt) < 2) {
           $this->holder = null;
           return;
       }
       $this->holder = &$bt[1][&#39;object&#39;];
   }
   
   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][&#39;object&#39;] !== $this->holder)
                || (count($bt) < 2))) {
           throw(new Exception(&#39;Notify can only be called in holder&#39;));   
       }
       foreach ($this->callbacks as $callback) {
           $args = func_get_args();
           call_user_func_array($callback, $args);
       }
   }
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:simplexml的对象转成数组Next article:将数组转换为XML