程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP實現事件機制實例分析

PHP實現事件機制實例分析

編輯:關於PHP編程

       本文實例講述了PHP實現事件機制的方法。分享給大家供大家參考。具體分析如下:

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

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 <?php /** * 事件 * * @author xiezhenye <[email protected]> */ 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程序設計有所幫助。

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved