閱讀559 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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();

?>

 

  

最後更新:2017-04-02 00:06:48

  上一篇:go java中屬性文件讀取的例子
  下一篇:go Opengl編程學習筆記(五)——從FRAGMENT到PIXEL(framebuffer 幀緩存)