VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > PHP >
  • php中注册器模式类用法实例分析

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

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

注册器读写类

Registry.class.php

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

需要注册的类

test.class.php

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

测试 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. ?>
  15.  

出处:http://www.phpfensi.com/php/20210624/16654.html


相关教程