這篇文章主要介紹了php中注冊器模式類用法,以實例形式分析了注冊器讀寫類的相關使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了php中注冊器模式類用法。分享給大家供大家參考,具體如下:
注冊器讀寫類
Registry.class.php
- <?php
- /**
- * 注冊器讀寫類
- */
- class Registry extends ArrayObject
- {
- /**
- * Registry實例
- *
- * @var object
- */
- private static $_instance = null;
- /**
- * 取得Registry實例
- *
- * @note 單件模式
- *
- * @return object
- */
- public static function getInstance()
- {
- if (self::$_instance === null) {
- self::$_instance = new self();
- echo "new register object!";
- }
- return self::$_instance;
- }
- /**
- * 保存一項內容到注冊表中
- *
- * @param string $name 索引
- * @param mixed $value 數據
- *
- * @return void
- */
- public static function set($name, $value)
- {
- self::getInstance()->offsetSet($name, $value);
- }
- /**
- * 取得注冊表中某項內容的值
- *
- * @param string $name 索引
- *
- * @return mixed
- */
- public static function get($name)
- {
- $instance = self::getInstance();
- if (!$instance->offsetExists($name)) {
- return null;
- }
- return $instance->offsetGet($name);
- }
- /**
- * 檢查一個索引是否存在
- *
- * @param string $name 索引
- *
- * @return boolean
- */
- public static function isRegistered($name)
- {
- return self::getInstance()->offsetExists($name);
- }
- /**
- * 刪除注冊表中的指定項
- *
- * @param string $name 索引
- *
- * @return void
- */
- public static function remove($name)
- {
- self::getInstance()->offsetUnset($name);
- }
- }
需要注冊的類
test.class.php
- <?php
- class Test
- {
- function hello()
- {
- echo "hello world";
- return;
- }
- }
- ?>
測試 test.php
- <?php
- //引入相關類
- require_once "Registry.class.php";
- require_once "test.class.php";
- //new a object
- $test=new Test();
- //$test->hello();
- //注冊對象
- Registry::set('testclass',$test);
- //取出對象
- $t = Registry::get('testclass');
- //調用對象方法
- $t->hello();
- ?>
希望本文所述對大家php程序設計有所幫助。
|
新聞熱點
疑難解答