note 57666 added to language.oop
| From: | FelixM.Palmen | Date: | Mon, 10 Oct 2005 20:18:57 +0000 |
| Subject: | note 57666 added to language.oop | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-96796@lists.php.net to get a copy of this message | ||
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;
}
}
}
?>
----
Manual Page -- http://www.php.net/manual/en/language.oop.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+57666
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+57666&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+57666&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+57666&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+57666&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+57666&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+57666&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+57666&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+57666&report=yes
Search -- http://master.php.net/manage/user-notes.php