当前位置:首页 > PHP教程 > php类库 > 列表

php中注册器模式类用法实例分析

发布:smiling 来源: PHP粉丝网  添加日期:2021-06-24 11:20:41 浏览: 评论:0 

这篇文章主要介绍了php中注册器模式类用法,以实例形式分析了注册器读写类的相关使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下。

本文实例讲述了php中注册器模式类用法,分享给大家供大家参考,具体如下:

注册器读写类

Registry.class.php

  1. <?php 
  2. /**  
  3.  * 注册器读写类  
  4.  */ 
  5. class Registry extends ArrayObject 
  6. { 
  7.   /**  
  8.    * Registry实例 
  9.    * 
  10.    * @var object  
  11.    */ 
  12.   private static $_instance = null; 
  13.   /** 
  14.    * 取得Registry实例 
  15.    *  
  16.    * @note 单件模式 
  17.    *  
  18.    * @return object 
  19.    */ 
  20.   public static function getInstance() 
  21.   { 
  22.     if (self::$_instance === null) { 
  23.       self::$_instance = new self(); 
  24.       echo "new register object!"; 
  25.     } 
  26.     return self::$_instance; 
  27.   } 
  28.   /** 
  29.    * 保存一项内容到注册表中 
  30.    *  
  31.    * @param string $name 索引 
  32.    * @param mixed $value 数据 
  33.    *  
  34.    * @return void 
  35.    */ 
  36.   public static function set($name, $value) 
  37.   { 
  38.     self::getInstance()->offsetSet($name, $value); 
  39.   } 
  40.   /** 
  41.    * 取得注册表中某项内容的值 
  42.    *  
  43.    * @param string $name 索引 
  44.    *  
  45.    * @return mixed 
  46.    */ 
  47.   public static function get($name) 
  48.   { 
  49.     $instance = self::getInstance(); 
  50.     if (!$instance->offsetExists($name)) { 
  51.       return null; 
  52.     } 
  53.     return $instance->offsetGet($name); 
  54.   } 
  55.   /** 
  56.    * 检查一个索引是否存在  
  57.    *  
  58.    * @param string $name 索引 
  59.    *  
  60.    * @return boolean 
  61.    */ 
  62.   public static function isRegistered($name) 
  63.   { 
  64.     return self::getInstance()->offsetExists($name); 
  65.   } 
  66.   /** 
  67.    * 删除注册表中的指定项 
  68.    *  
  69.    * @param string $name 索引 
  70.    *  
  71.    * @return void 
  72.    */ 
  73.   public static function remove($name) 
  74.   { 
  75.     self::getInstance()->offsetUnset($name); 
  76.   } 
  77. } 

需要注册的类

test.class.php

  1. <?php 
  2. class Test 
  3. { 
  4.    function hello() 
  5.    { 
  6.     echo "hello world"; 
  7.     return; 
  8.    } 
  9. }  
  10. ?> 

测试 test.php

  1. <?php 
  2. //引入相关类 
  3. require_once "Registry.class.php"; 
  4. require_once "test.class.php"; 
  5. //new a object 
  6. $test=new Test(); 
  7. //$test->hello(); 
  8. //注册对象 
  9. Registry::set('testclass',$test); 
  10. //取出对象 
  11. $t = Registry::get('testclass'); 
  12. //调用对象方法 
  13. $t->hello(); 
  14. ?>

Tags: php注册器模式类

分享到: