Posted By

ekobudisetiyo on 07/14/06


Tagged

pattern php5 Singleton


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

jonbaer
tikitakfire
shikee


PHP5 Singleton Class


 / Published in: PHP
 

URL: http://fuselogic.haltebis.com

Actually Singleton Class in PHP5 is very easy. Usage:

  1. //PHP5 only
  2.  
  3. class singleton_helper
  4. {
  5. var $__x = array();
  6. public static function singleton()
  7. {
  8. static $class = null;
  9. if($class == null)
  10. {
  11. $c = __CLASS__;
  12. $class = new $c;
  13. }
  14. return $class;
  15. }
  16. function __construct(){}
  17.  
  18. function __get($name)
  19. {
  20. $name = strtolower($name);
  21. if(isset($this->__x[$name]))
  22. {
  23. return $this->__x[$name];
  24. }
  25. }
  26.  
  27. function __set($name,$val)
  28. {
  29. $this->__x[strtolower($name)] = $val;
  30. }
  31.  
  32. function __isset($name)
  33. {
  34. return isset($this->__x[strtolower($name)]);
  35. }
  36. }
  37.  
  38. class singleton
  39. {
  40. var $____variable;
  41. function __construct()
  42. {
  43. $name = get_class($this);
  44. if(!isset(singleton_helper::singleton()->{$name}))
  45. {
  46. singleton_helper::singleton()->{$name} = new singleton_helper();
  47. }
  48. $this->____variable = &singleton_helper::singleton()->{$name};
  49. }
  50.  
  51. function __set($name,$value)
  52. {
  53. $this->____variable->$name = $value;
  54. }
  55.  
  56. function __get($name)
  57. {
  58. return $this->____variable->$name;
  59. }
  60.  
  61. function __isset($name)
  62. {
  63. return isset($this->____variable->$name);
  64. }
  65. }
  66.  
  67. //Unit Test Bellow
  68. class singleton_x extends singleton
  69. {
  70. function __cunstruct()
  71. {
  72. parent::__construct();
  73. }
  74.  
  75. function test()
  76. {
  77. return 'test';
  78. }
  79. }
  80.  
  81. class singleton_y extends singleton_x
  82. {
  83. function __cunstruct()
  84. {
  85. parent::__construct();
  86. }
  87. }
  88.  
  89. class TestOfSingleton extends UnitTestCase
  90. {
  91. function __construct()
  92. {
  93. $this->UnitTestCase();
  94. }
  95.  
  96. function test_one()
  97. {
  98. $test1 = new singleton_x();
  99. $test1->a = 1;
  100. $this->assertEqual(1,$test1->a);
  101.  
  102. $test2 = new singleton_x();
  103. $this->assertEqual(1,$test2->a);
  104.  
  105. $test2->a = 'abc';
  106. $this->assertEqual('abc',$test1->a);
  107. }
  108.  
  109. function test_two()
  110. {
  111. $test1 = new singleton_y();
  112. $test1->a = 1;
  113. $this->assertEqual(1,$test1->a);
  114.  
  115. $test2 = new singleton_y();
  116. $this->assertEqual(1,$test2->a);
  117.  
  118. $this->assertEqual('test',$test1->test());
  119. }
  120. }

Report this snippet  

You need to login to post a comment.