PHP-based event mechanism instance analysis and php-based instance analysis. PHP-based event mechanism instance analysis. php-based instance analysis this article describes the PHP-based event mechanism. Share it with you for your reference. The specific analysis is as follows: built-in event mechanism instance analysis based on PHP, and php mechanism instance analysis
This example describes the PHP-based event mechanism. 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
* @ 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 ($ arg S [0]) & is_string ($ args [1]) {$ this-> callbacks [] = array (& $ args [0], $ args [1]);} return; default: return ;}} function using 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.
The example in this article describes the PHP-based event mechanism. Share it with you for your reference. The specific analysis is as follows: built-in...