This article mainly introduces how PHP implements the event mechanism. The example analyzes the principles of the event mechanism and php implementation skills, for more information about how to implement the event mechanism in PHP, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
There are not many languages with built-in event mechanisms, and php does not provide such a function. Event is simply an Observer mode, which is easy to implement. However, the difference is that all event listeners can be added, but they can only be triggered by objects that directly contain the event. This is a little difficult. Php has a debug_backtrace function, which can obtain the current call stack and find a way to determine whether the object that calls the event-triggered function directly contains the object.
<? 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 Y () {$ bt = debug_backtrace (); if ($ this-> holder & (count ($ bt)> = 2 & $ bt [count ($ bt)-1] ['object']! ==$ This-> holder) | (count ($ bt) <2) {throw (new Exception ('allow Y can only be called in holder '));} foreach ($ this-> callbacks as $ callback) {$ args = func_get_args (); call_user_func_array ($ callback, $ args );}}}
I hope this article will help you with php programming.