您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP事件机制的原理

2026/1/28 6:12:34发布15次查看
本篇文章主要介绍php事件机制的原理,感兴趣的朋友参考下,希望对大家有所帮助。
本文实例讲述了php实现事件机制的方法,具体分析如下:
内置了事件机制的语言不多,php也没有提供这样的功能。事件(event)说简单了就是一个observer模式,实现起来很容易。但是有所不同的是,事件的监听者谁都可以加,但是只能由直接包含它的对象触发。这就有一点点难度了。php有一个debug_backtrace函数,可以得到当前的调用栈,由此可以找到判断调用事件触发函数的对象是不是直接包含它的对象的办法。
<?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利用正则表达式提取内容中的链接
php实现汉字验证码
php实现加载字体并保存
以上就是php事件机制的原理的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product