note 57666 deleted from language.oop by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 19:03:20 +0000 |
| Subject: | note 57666 deleted from language.oop by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162559@lists.php.net to get a copy of this message | ||
Note Submitter: Felix M dot Palmen <fmp at palmen dot homeip dot net>
----
My way to implement a singleton in PHP4. I think it's the most convenient one since it works
transparently using the constructor. Thanks to S.Radovanovic for his idea with referencing the
class' variables, posted on http://www.php.net/manual/en/language.variables.scope.php
<?php
/* Singleton. Every instatiation returns the "same" object.
*
* for this to work, ALWAYS create objects with $object =& new class().
* The reference operator doesn't do any harm in general and is
* necessary for singletons.
*
* You also need to declare all the class' variables with "var" for
* a singleton subclass. But that should always be a rule of good
* design :)
*
* call parent::singleton() first in your subclass constructor.
*
* Of course, the subclass constructor should check if the object is already
* initialized before doing any initialization.
*/
class singleton
{
function singleton()
{
// static associative array containing the real objects, key is classname
static $instances=array();
// get classname
$class = get_class($this);
if (!array_key_exists($class, $instances))
{
// does not yet exist, save in array
$instances[$class] = $this;
}
// PHP doesn't allow us to assign a reference to $this, so we do this
// little trick and fill our new object with references to the original
// class' variables:
foreach (get_class_vars($class) as $var => $value)
{
$this->$var =& $instances[$class]->$var;
}
}
}
?>