首页 > 开发 > PHP > 正文

PHP实现事件机制的方法

2024-05-04 23:37:40
字体:
来源:转载
供稿:网友

这篇文章主要介绍了PHP实现事件机制的方法,实例分析了php针对事件机制的定义与实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了PHP实现事件机制的方法。分享给大家供大家参考。具体如下:

 

 
  1. <?php 
  2. /** 
  3. * 事件 
  4. */ 
  5. class Event { 
  6. private $callbacks = array(); 
  7. private $holder
  8. function __construct() { 
  9. $bt = debug_backtrace(); 
  10. if (count($bt) < 2) { 
  11. $this->holder = null; 
  12. return
  13. $this->holder = &$bt[1]['object']; 
  14. function attach() { 
  15. $args = func_get_args(); 
  16. switch (count($args)) { 
  17. case 1: 
  18. if (is_callable($args[0])) { 
  19. $this->callbacks[]= $args[0]; 
  20. return
  21. break
  22. case 2: 
  23. if (is_object($args[0]) && is_string($args[1])) { 
  24. $this->callbacks[]= array(&$args[0], $args[1]); 
  25. return
  26. default
  27. return
  28. function notify() { 
  29. $bt = debug_backtrace(); 
  30. if ($this->holder &&  
  31. ((count($bt) >= 2 && $bt[count($bt) - 1]['object'] !== $this->holder) 
  32. || (count($bt) < 2))) { 
  33. throw(new Exception('Notify can only be called in holder')); 
  34. foreach ($this->callbacks as $callback) { 
  35. $args = func_get_args(); 
  36. call_user_func_array($callback$args); 

希望本文所述对大家的php程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表