note 63306 deleted from language.oop5.patterns by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 16:45:10 +0000 |
| Subject: | note 63306 deleted from language.oop5.patterns by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176118@lists.php.net to get a copy of this message | ||
Note Submitter: contact_us at haltebis dot com
----
Here is my PHP5 Singleton only ("no getInstances()")
<?php
#file class.singleton.php
class singleton
{
var $instance;
function __construct()
{
static $instances=array();
$class = get_class($this);
if(!isset($instances[$class])) $instances[$class] = $this;
foreach(get_class_vars($class) as $var => $value)
{
$this->$var = &$instances[$class]->$var;
}
$this->instance = &$instances[$class];
}
function __set($name,$value)
{
$this->$name = $value;
if(!isset($this->instance->$name)) $this->instance->$name = &$this->$name;
}
}
?>
And here is the SimpleTest unit that I use
<?php
#file test.singleton.php
class singleton_example extends singleton
{
var $x;
var $y;
function __construct()
{
parent::__construct();
}
}
class singleton_example2 extends singleton
{
var $x;
var $y;
function __construct()
{
parent::__construct();
}
}
class TestOfSingleton extends UnitTestCase
{
function TestOfSingleton()
{
$this->UnitTestCase();
}
function testSet_and_Get1()
{
$test1 = new singleton_example();
$test1->x = 'a';;
$test1->y = 'b';
$test2 = new singleton_example();
$test2->x = 'c';
$test2->y = 'd';
$test2->z = 'e';
$test3 = new singleton_example2();
$this->assertEqual($test1->x,'c');
$this->assertEqual($test1->y,'d');
$this->assertEqual($test1->z,'e');
$this->assertEqual($test3->x,null);
$this->assertEqual($test3->y,null);
}
}
?>
Never failed me until now