PHP PHP5 Singleton类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP PHP5 Singleton类相关的知识,希望对你有一定的参考价值。

//PHP5 only

class singleton_helper
{
   var $__x = array();
   public static function singleton()
   {
      static $class = null;
      if($class == null)
      {
         $c = __CLASS__;
         $class = new $c;
      }
      return $class;
   }
   function __construct(){}

   function __get($name)
   {
       $name = strtolower($name);
       if(isset($this->__x[$name]))
       {
          return $this->__x[$name];
       }
   }

   function __set($name,$val)
   {
       $this->__x[strtolower($name)] = $val;
   }

   function __isset($name)
   {
      return isset($this->__x[strtolower($name)]);
   }
}

class singleton
{
   var $____variable;
   function __construct()
   {
      $name = get_class($this);
      if(!isset(singleton_helper::singleton()->{$name}))
      {
         singleton_helper::singleton()->{$name} = new singleton_helper();
      }
      $this->____variable = &singleton_helper::singleton()->{$name};
   }

   function __set($name,$value)
   {
       $this->____variable->$name = $value;
   }

   function __get($name)
   {
      return $this->____variable->$name;
   }

   function __isset($name)
   {
      return isset($this->____variable->$name);
   }
}

//Unit Test Bellow
class singleton_x extends singleton
{
   function __cunstruct()
   {
      parent::__construct();
   }

   function test()
   {
      return 'test';
   }	  
}

class singleton_y extends singleton_x
{
   function __cunstruct()
   {
      parent::__construct();
   }
}

class TestOfSingleton extends UnitTestCase
{
   function __construct()
   {
      $this->UnitTestCase();
   }

   function test_one()
   {
       $test1 = new singleton_x();
	   $test1->a = 1;	   
       $this->assertEqual(1,$test1->a);
       
	   $test2 = new singleton_x();       
	   $this->assertEqual(1,$test2->a);

	   $test2->a = 'abc';
	   $this->assertEqual('abc',$test1->a);
   }
   
   function test_two()
   {
       $test1 = new singleton_y();
	   $test1->a = 1;	   
       $this->assertEqual(1,$test1->a);
       
	   $test2 = new singleton_y();       
	   $this->assertEqual(1,$test2->a);

	   $this->assertEqual('test',$test1->test());
   }
}

以上是关于PHP PHP5 Singleton类的主要内容,如果未能解决你的问题,请参考以下文章

PHP PHP5中的简单类示例

PHP PHP5 Session Wraper类

php5类,用于easybots

实例化时自动加载PHP类(PHP5)

php aes加密解密类(兼容php5php7)

高级类/接口自动加载PHP5.3方式