/ Published in: PHP
Actually Singleton Class in PHP5 is very easy.
Usage:
Usage:
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
//PHP5 only class singleton_helper { public static function singleton() { static $class = null; if($class == null) { $c = __CLASS__; $class = new $c; } return $class; } function __construct(){} function __get($name) { { return $this->__x[$name]; } } function __set($name,$val) { } function __isset($name) { } } class singleton { var $____variable; function __construct() { { 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) { } } //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()); } }
URL: http://fuselogic.haltebis.com