note 80469 deleted from language.oop5.patterns by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 16:41:48 +0000 |
| Subject: | note 80469 deleted from language.oop5.patterns by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176108@lists.php.net to get a copy of this message | ||
Note Submitter: me at chrisstockton dot org
----
For anyone who reads: tims57 at yahoo dot com
Please let me show everyone a example of how a global variable is nothing like a singleton pattern.
Take into considering the following. A global variable, cares not the state of its contents, it is
only a container. If it contains a instance, a boolean, or a integer, it is all the same to it as
PHP is dynamically typed it would be very easy for a global variable to be overridden by some
dynamically loaded module in a complicated architecture, which could in turn cause a instance that
maintains account or billing data to destruct before values are written to it.
The singleton is a means of protecting the instance to a single instantiation.
A global variable offers no such protection, it is only a container for a value.
<?php
$unreliableInstanceNotProtectedAtAll = new StdClass;
class Singleton
{
static private $_instance;
private $_foo = 'foo';
private function __construct() {}
static public function getInstance() {
return isset(self::$_instance) ?
self::$_instance : self::$_instance = new self();
}
public function updateFoo($foo) {
$this->_foo = $foo;
}
public function getFoo() {
return $this->_foo;
}
}
/** Singleton offers protection from being instantiated multiple times */
// file_2481_r4.php, the early foo module not used except under certain circumstances
$foo = Singleton::getInstance();
var_dump($foo->getFoo()); // foo
$foo->updateFoo('bar');
var_dump($foo->getFoo()); // bar
// file_1444114_r1.php (author has no idea that file_2481_r4.php was loaded by
// the "foo" module", doesn't matter because the class will be instantiated only
once
$foo = Singleton::getInstance();
var_dump($foo->getFoo()); // bar
/** Global variable just contains a instance, has no care for what it contains */
// file_2481_r4.php, the early foo module not used except under certain circumstances
$unreliableInstanceNotProtectedAtAll->foo = 'foo';
// file_1444114_r1.php (author has no idea that file_2481_r4.php was loaded by
// the "foo" module", doesn't matter because the class will be instantiated only
once
$unreliableInstanceNotProtectedAtAll = new StdClass;
$unreliableInstanceNotProtectedAtAll->foo = 'bar';
?>