An example analysis of the event mechanism based on PHP implementation, a case study of PHP mechanism
This article describes the event mechanism based on PHP implementation. 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
* @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 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/1019078.html www.bkjia.com true http://www.bkjia.com/PHPjc/1019078.html techarticle The case analysis of the event mechanism based on PHP implementation, the example of PHP mechanism is analyzed in this paper, and the event mechanism based on PHP implementation is described. Share to everyone for your reference. The specific analysis is as follows: Built-in ...