PHP Implementation Event Mechanism example analysis, PHP event instance analysis
In this paper, we describe the method of implementing event mechanism in PHP. Share to everyone for your reference. The specific analysis is as follows:
There are not many languages built into the event mechanism, and PHP does not provide such a feature. Event is simply a observer mode that is easy to implement. But the difference is that the listener of the event can add it, but only the object that directly contains it triggers. This is a little bit more difficult. PHP has a debug_backtrace function that allows you to get the current call stack, so that you can find out whether the object that invokes the event trigger function is the object that directly contains it.
<?php/*** Event * * @author Xiezhenye
*/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 is called in Holder ')); } foreach ($this->callbacks as $callback) {$args = Func_get_args (); Call_user_func_array ($callback, $args); } }}
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/1022778.html www.bkjia.com true http://www.bkjia.com/PHPjc/1022778.html techarticle PHP Implementation Event Mechanism example analysis, PHP event Instance Analysis This article describes the PHP implementation of the event mechanism method. Share to everyone for your reference. The specific analysis is as follows: Built-in events ...