《PHP教程:PHP實(shí)現(xiàn)事件機(jī)制實(shí)例分析》要點(diǎn):
本文介紹了PHP教程:PHP實(shí)現(xiàn)事件機(jī)制實(shí)例分析,希望對您有用。如果有疑問,可以聯(lián)系我們。
本文實(shí)例講述了PHP實(shí)現(xiàn)事件機(jī)制的辦法.分享給大家供大家參考.具體分析如下:PHP編程
內(nèi)置了事件機(jī)制的語言不多,php也沒有提供這樣的功能.事件(Event)說簡單了就是一個Observer模式,實(shí)現(xiàn)起來很容易.但是有所不同的是,事件的監(jiān)聽者誰都可以加,但是只能由直接包含它的對象觸發(fā).這就有一點(diǎn)點(diǎn)難度了.php有一個debug_backtrace函數(shù),可以得到當(dāng)前的調(diào)用棧,由此可以找到判斷調(diào)用事件觸發(fā)函數(shù)的對象是不是直接包含它的對象的方法.PHP編程
<?php /** * 事件 * * @author xiezhenye <xiezhenye@gmail.com> */ 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程序設(shè)計有所贊助.PHP編程
《PHP教程:PHP實(shí)現(xiàn)事件機(jī)制實(shí)例分析》是否對您有啟發(fā),歡迎查看更多與《PHP教程:PHP實(shí)現(xiàn)事件機(jī)制實(shí)例分析》相關(guān)教程,學(xué)精學(xué)透。維易PHP學(xué)院為您提供精彩教程。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/10036.html