亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

基于PHP實現(xiàn)的事件機制實例分析

 更新時間:2015年06月18日 09:39:46   作者:瘋狂的流浪  
這篇文章主要介紹了基于PHP實現(xiàn)的事件機制,實例分析了事件機制的原理及php中debug_backtrace函數(shù)完成事件機制的實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了基于PHP實現(xiàn)的事件機制。分享給大家供大家參考。具體分析如下:

內(nèi)置了事件機制的語言不多,php也沒有提供這樣的功能。事件(Event)說簡單了就是一個Observer模式,實現(xiàn)起來很容易。但是有所不同的是,事件的監(jiān)聽者誰都可以加,但是只能由直接包含它的對象觸發(fā)。這就有一點點難度了。php有一個debug_backtrace函數(shù),可以得到當前的調(diào)用棧,由此可以找到判斷調(diào)用事件觸發(fā)函數(shù)的對象是不是直接包含它的對象的辦法。

<?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]['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程序設計有所幫助。

相關(guān)文章

最新評論